Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 木雨音樂 項目開發(四)本地音樂MyMusicListFragment

木雨音樂 項目開發(四)本地音樂MyMusicListFragment

編輯:關於Android編程

1、加載本地音樂

2、單擊列表實現播

在建立MyMusicListFragment.java前先建立值對象Mp3Info.java

Mp3Info.java代碼如下

包含了歌曲的一些信息

package com.haoxue.zixueplayer.vo;

/**
 * Created by Administrator on 2016/7/27.
 */
public class Mp3Info {
    private long id;
    private long mp3InfoId;//在收藏音樂時用於保存原始ID
    private long playTime;//最勁播放時間
    private int isLike;//1 喜歡  0 默認
    private String title;//歌名
    private String artist;//藝術家
    private String album;//專輯
    private long albumId;
    private long duration;//時長
    private long size;//大小
    private String url;//路徑
    private int isMusic;//是否為音樂
    private String displayName;//文件名


    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public long getPlayTime() {
        return playTime;
    }
    public void setPlayTime(long playTime) {
        this.playTime = playTime;
    }
    public int getIsLike() {
        return isLike;
    }
    public void setIsLike(int isLike) {
        this.isLike = isLike;
    }
    public long getMp3InfoId() {
        return mp3InfoId;
    }
    public void setMp3InfoId(long mp3InfoId) {
        this.mp3InfoId = mp3InfoId;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getArtist() {
        return artist;
    }
    public void setArtist(String artist) {
        this.artist = artist;
    }
    public String getAlbum() {
        return album;
    }
    public void setAlbum(String album) {
        this.album = album;
    }
    public long getAlbumId() {
        return albumId;
    }
    public void setAlbumId(long albumId) {
        this.albumId = albumId;
    }
    public long getDuration() {
        return duration;
    }
    public void setDuration(long duration) {
        this.duration = duration;
    }
    public long getSize() {
        return size;
    }
    public void setSize(long size) {
        this.size = size;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public int getIsMusic() {
        return isMusic;
    }
    public void setIsMusic(int isMusic) {
        this.isMusic = isMusic;
    }

    @Override
    public String toString() {
        return "Mp3Info{" +
                "id=" + id +
                ", mp3InfoId=" + mp3InfoId +
                ", playTime=" + playTime +
                ", isLike=" + isLike +
                ", title='" + title + '\'' +
                ", artist='" + artist + '\'' +
                ", album='" + album + '\'' +
                ", albumId=" + albumId +
                ", duration=" + duration +
                ", size=" + size +
                ", url='" + url + '\'' +
                ", isMusic=" + isMusic +
                ", displayName='" + displayName + '\'' +
                '}';
    }
}

建立本地音樂列表適配器MyMusicListAdapter.java代碼如下

package com.haoxue.zixueplayer.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.haoxue.zixueplayer.R;
import com.haoxue.zixueplayer.utils.MediaUtils;
import com.haoxue.zixueplayer.vo.Mp3Info;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/7/27.
 * 本地列表適配器
 */
public class MyMusicListAdapter extends BaseAdapter {

    private Context ctx;
    private ArrayList mp3Infos;
    private Mp3Info mp3Info;		//Mp3Info對象引用
    private int pos = -1;			//列表位置

    public MyMusicListAdapter(Context ctx, ArrayList mp3Infos) {
        this.ctx = ctx;
        this.mp3Infos = mp3Infos;
    }

    public ArrayList getMp3Infos() {
        return mp3Infos;
    }
    public void setMp3Infos(ArrayList mp3Infos) {
        this.mp3Infos = mp3Infos;
    }

    @Override
    public int getCount() {
        return mp3Infos.size();
    }

    @Override
    public Object getItem(int position) {
        return mp3Infos.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh;
        if (convertView == null) {
            convertView= LayoutInflater.from(ctx).inflate(R.layout.item_music_list,null);
            vh=new ViewHolder();
            vh.textView1_title= (TextView) convertView.findViewById(R.id.textView1_title);
            vh.textView2_singer= (TextView) convertView.findViewById(R.id.textView2_singer);
            vh.textView3_time= (TextView) convertView.findViewById(R.id.textView3_time);
            convertView.setTag(vh);
        }else {
            vh= (ViewHolder) convertView.getTag();
        }
        Mp3Info mp3Info=mp3Infos.get(position);
        vh.textView1_title.setText(mp3Info.getTitle());
        vh.textView2_singer.setText(mp3Info.getArtist());
        vh.textView3_time.setText(MediaUtils.formatTime(mp3Info.getDuration()));


        return convertView;
    }


    static class ViewHolder{
        TextView textView1_title;
        TextView textView2_singer;
        TextView textView3_time;
    }
}

建立媒體工具類MediaUtils.java,在系統媒體數據庫內獲取音樂信息,自定義專輯圖片工具,代碼如下

package com.haoxue.zixueplayer.utils;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;

import com.haoxue.zixueplayer.R;
import com.haoxue.zixueplayer.vo.Mp3Info;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2016/7/27.
 */
@SuppressWarnings("ResourceType")
public class MediaUtils {

    //獲取專輯封面的Uri
    private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");

    /**
     * 根據歌曲id查詢歌曲信息
     *
     * @param context
     * @param _id
     * @return
     */
//    public static Mp3Info getMp3Info(Context context, long _id) {
//        //System.out.println(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
//        Cursor cursor = context.getContentResolver().query(
//                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
//                MediaStore.Audio.Media._ID + "=" + _id, null,
//                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//
//        Mp3Info mp3Info = null;
//
//        if (cursor.moveToNext()) {
//            mp3Info = new Mp3Info();
//            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));//音樂id
//            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));//音樂標題
//            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));//藝術家
//            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));//專輯
//            long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
//            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//時長
//            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));//文件大小
//            String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));//文件路徑
//            int ismusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否為音樂
//            if (ismusic != 0) {//只把音樂添加到集合當中
//                mp3Info.setId(id);
//                mp3Info.setTitle(title);
//                mp3Info.setArtist(artist);
//                mp3Info.setAlbum(album);
//                mp3Info.setAlbumId(albumId);
//                mp3Info.setDuration(duration);
//                mp3Info.setSize(size);
//                mp3Info.setUrl(url);
//            }
//        }
//        cursor.close();
//        return mp3Info;
//    }

    /**
     * 用於從數據庫中查詢歌曲的信息,保存在list當中
     *
     * @param context
     * @return
     */
//    public static long[] getMp3InfoIds(Context context) {
//        Cursor cursor = context.getContentResolver().query(
//                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
//                new String[]{MediaStore.Audio.Media._ID},
//                MediaStore.Audio.Media.DURATION + ">=90000", null,
//                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//        long[] ids = null;
//        if (cursor != null) {
//            ids = new long[cursor.getCount()];
//            for (int i = 0; i < cursor.getCount(); i++) {
//                cursor.moveToNext();
//                ids[i] = cursor.getLong(0);
//            }
//        }
//        cursor.close();
//        return ids;
//    }

    /**
     * 用於從數據庫中查詢歌曲的信息,保存在list當中
     *
     * @param context
     * @return
     */
    public static ArrayList getMp3Infos(Context context) {
//        System.out.println("我在這"+MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,
                MediaStore.Audio.Media.DURATION + ">=15000", null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        ArrayList mp3Infos = new ArrayList();
        assert cursor != null;
        for (int i = 0; i < cursor.getCount(); i++) {
            cursor.moveToNext();
            Mp3Info mp3Info = new Mp3Info();
            long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media._ID));//音樂id
            String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));//音樂標題
            String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));//藝術家
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));//專輯
            long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));//時長
            long size = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.SIZE));//文件大小
            String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));//文件路徑
            int ismusic = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC));//是否為音樂
            String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));//文件名
            if (ismusic != 0) {//只把音樂添加到集合當中

                mp3Info.setId(id);
                mp3Info.setTitle(title);
                if (artist.equals("")) {
                    mp3Info.setArtist("未知歌手");
                } else {
                    mp3Info.setArtist(artist);
                }
                mp3Info.setAlbum(album);
                mp3Info.setAlbumId(albumId);
                mp3Info.setDuration(duration);
                mp3Info.setSize(size);
                mp3Info.setUrl(url);
                mp3Info.setDisplayName(displayName);
                mp3Infos.add(mp3Info);
            }
        }
        cursor.close();
        return mp3Infos;

    }

    /**
     * 往List集合中添加Map對象數據,每一個Map對象存放一首音樂的所有屬性
     *
     * @param mp3Infos
     * @return
     */
    public static List> getMusicMaps(
            List mp3Infos) {
        List> mp3list = new ArrayList<>();
        for (Iterator iterator = mp3Infos.iterator(); iterator.hasNext(); ) {
            Mp3Info mp3Info = (Mp3Info) iterator.next();
            HashMap map = new HashMap<>();
            map.put("title", mp3Info.getTitle());
            map.put("Artist", mp3Info.getArtist());
            map.put("album", mp3Info.getAlbum());
            map.put("albumId", String.valueOf(mp3Info.getAlbumId()));
            map.put("duration", formatTime(mp3Info.getDuration()));
            map.put("size", String.valueOf(mp3Info.getSize()));
            map.put("url", mp3Info.getUrl());
            mp3list.add(map);
        }
        return mp3list;
    }

    /**
     * 格式化時間,將毫秒轉換成為分:秒格式
     *
     * @param time
     * @return
     */
    public static String formatTime(long time) {
        String min = time / (1000 * 60) + "";
        String sec = time % (1000 * 60) + "";
        if (min.length() < 2) {
            min = "0" + time / (1000 * 60) + "";
        } else {
            min = time / (1000 * 60) + "";
        }
        if (sec.length() == 4) {
            sec = "0" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 3) {
            sec = "00" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 2) {
            sec = "000" + (time % (1000 * 60)) + "";
        } else if (sec.length() == 1) {
            sec = "0000" + (time % (1000 * 60)) + "";
        }
        return min + ":" + sec.trim().substring(0, 2);
    }

    /**
     * 獲取默認專輯圖片
     *
     * @param context
     * @param small
     * @return
     */
    public static Bitmap getDefaultArtwork(Context context, boolean small) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inPreferredConfig = Bitmap.Config.RGB_565;
        if (small) {//返回小圖片
            return BitmapFactory.decodeStream(context.getResources()
                    .openRawResource(R.mipmap.music), null, opts);
        }
        return BitmapFactory.decodeStream(context.getResources()
                .openRawResource(R.mipmap.defaultalbum), null, opts);
    }

    /**
     * 從文件當中獲取專輯封面位圖
     *
     * @param context
     * @param songid
     * @param albumid
     * @return
     */
    private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
        Bitmap bm = null;
        if (albumid < 0 && songid < 0) {
            throw new IllegalArgumentException("Must specify an album or a song id");
        }
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            FileDescriptor fd = null;
            if (albumid < 0) {
                Uri uri = Uri.parse("content://media/external/audio/media" + songid + "/albumart");
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            } else {
                Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);
                ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
                if (pfd != null) {
                    fd = pfd.getFileDescriptor();
                }
            }
            options.inSampleSize = 1;
            //只進行大小判斷
            options.inJustDecodeBounds = true;
            //調用此方法得到options得到圖片的大小
            BitmapFactory.decodeFileDescriptor(fd, null, options);
            //我們的目標是在800pixel的畫面上顯示
            //所以需要調用computeSampleSize得到圖片縮放的比例
            options.inSampleSize = 100;
            //我們得到縮放比例,現在開始正式讀入Bitmap數據
            options.inJustDecodeBounds = false;
            options.inDither = false;
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;

            //根據options參數,減少所需要的內存
            bm = BitmapFactory.decodeFileDescriptor(fd, null, options);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * 獲取專輯封面位圖對象
     *
     * @param context
     * @param song_id
     * @param album_id
     * @param allowdefalut
     * @param small
     * @return
     */
    public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small) {
        if (album_id < 0) {
            if (song_id < 0) {
                Bitmap bm = getArtworkFromFile(context, song_id, -1);
                if (bm != null) {
                    return bm;
                }
            }
            if (allowdefalut) {
                return getDefaultArtwork(context, small);
            }
            return null;
        }
        ContentResolver res = context.getContentResolver();
        Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);
        if (uri != null) {
            InputStream in = null;
            try {
                in = res.openInputStream(uri);
                BitmapFactory.Options options = new BitmapFactory.Options();
                //先制定原始大小
                options.inSampleSize = 1;
                //只進行大小判斷
                options.inJustDecodeBounds = true;
                //調用此方法得到options得到圖片的大小
                BitmapFactory.decodeStream(in, null, options);
                /**我們的目的是在你N pixel的畫面上顯示。所以需要調用computeSampleSize得到圖片縮放的比例**/
                /**這裡的target為800是根據默認專輯圖片大小決定的,800只是測試數字但是實驗後發現完美的結合**/
                if (small) {
                    options.inSampleSize = computeSampleSize(options, 40);
                } else {
                    options.inSampleSize = computeSampleSize(options, 600);
                }
                //我們得到了縮放比例,現在開始正式讀入Bitmap數據
                options.inJustDecodeBounds = false;
                options.inDither = false;
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                in = res.openInputStream(uri);
                return BitmapFactory.decodeStream(in, null, options);
            } catch (FileNotFoundException e) {
                Bitmap bm = getArtworkFromFile(context, song_id, album_id);
                if (bm != null) {
                    if (bm.getConfig() == null) {
                        bm = bm.copy(Bitmap.Config.RGB_565, false);
                        if (bm == null && allowdefalut) {
                            return getDefaultArtwork(context, small);
                        }
                    }
                } else if (allowdefalut) {
                    bm = getDefaultArtwork(context, small);
                }
                return bm;
            } finally {
                try {
                    if (in != null) {

                        in.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static int computeSampleSize(BitmapFactory.Options options, int target) {
        int w = options.outWidth;
        int h = options.outHeight;
        int candidateW = w / target;
        int candidateH = h / target;
        int candidate = Math.max(candidateW, candidateH);
        if (candidate == 0) {
            return 1;
        }
        if (candidate > 1) {
            if ((w > target) && (w / candidate < target)) {
                candidate -= 1;
            }
        }
        if (candidate > 1) {
            if ((h > target) && (h / candidate < target)) {
                candidate -= 1;
            }
        }
        return candidate;
    }

    /**
     * 獨立的倒影圖像
     *
     * @param src
     * @return
     */
    public static Bitmap createReflectionBitmapForSingle(Bitmap src) {
        final int w = src.getWidth();
        final int h = src.getHeight();
        // 繪制高質量32位圖
        Bitmap bitmap = Bitmap.createBitmap(w, h / 2, Bitmap.Config.ARGB_8888);
        // 創建沿X軸的倒影圖像
        Matrix m = new Matrix();
        m.setScale(1, -1);
        Bitmap t_bitmap = Bitmap.createBitmap(src, 0, h / 2, w, h / 2, m, true);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        // 繪制倒影圖像
        canvas.drawBitmap(t_bitmap, 0, 0, paint);
        // 線性渲染-沿Y軸高到低渲染
        Shader shader = new LinearGradient(0, 0, 0, h / 2, 0x70ffffff,
                0x00ffffff, Shader.TileMode.MIRROR);
        paint.setShader(shader);
        // 取兩層繪制交集。顯示下層。
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        // 繪制渲染倒影的矩形
        canvas.drawRect(0, 0, w, h / 2, paint);
        return bitmap;
    }

}

下面是MyMusicListFragment.java類,因為項目代碼已完成所以是完整代碼,實現了加載本地音樂、點擊列表順序播放、長按列表(播放、設為鈴聲、查看詳情、刪除音樂)功能,用到了上一節CustomDialog.java(自定義對話框類)具體代碼如下

package com.haoxue.zixueplayer;

import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.haoxue.zixueplayer.adapter.MyMusicListAdapter;
import com.haoxue.zixueplayer.utils.Constant;
import com.haoxue.zixueplayer.utils.ConstantUtil;
import com.haoxue.zixueplayer.utils.CustomDialog;
import com.haoxue.zixueplayer.utils.MediaUtils;
import com.haoxue.zixueplayer.vo.Mp3Info;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by Administrator on 2016/7/27.
 */
public class MyMusicListFragment extends Fragment implements AdapterView.OnItemClickListener, View.OnClickListener,AdapterView.OnItemLongClickListener {

    private ListView listView_my_music;
    private ImageView imageView_album;
    private TextView textView_songName, textView2_singer;
    private ImageView imageView2_play_pause, imageView3_next;
    private ArrayList mp3Infos;
    private MyMusicListAdapter myMusicListAdapter;

    private MuyuPlayerApp app;
    private MainActivity mainActivity;

    private int listposition = 0;// 標識列表位置



    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mainActivity = (MainActivity) context;
    }

    public static MyMusicListFragment newInstance() {
        MyMusicListFragment my = new MyMusicListFragment();
        return my;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.my_music_list_layout, null);
        listView_my_music = (ListView) view.findViewById(R.id.listView_my_music);
        imageView_album = (ImageView) view.findViewById(R.id.imageView_album);
        imageView2_play_pause = (ImageView) view.findViewById(R.id.imageView2_play_pause);
        imageView3_next = (ImageView) view.findViewById(R.id.imageView3_next);
        textView_songName = (TextView) view.findViewById(R.id.textView_songName);
        textView2_singer = (TextView) view.findViewById(R.id.textView2_singer);

        listView_my_music.setOnItemClickListener(this);
        listView_my_music.setOnItemLongClickListener(this);
        imageView2_play_pause.setOnClickListener(this);
        imageView3_next.setOnClickListener(this);
        imageView_album.setOnClickListener(this);


//        loadData();
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        //綁定播放服務
        mainActivity.bindPlayService();
    }

    @Override
    public void onPause() {
        super.onPause();
        //解除綁定播放服務
        mainActivity.unbindPlayService();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //暫改
        mainActivity.unbindPlayService();
    }

    /**
     * 加載本地音樂列表
     */
    public void loadData() {
        mp3Infos = MediaUtils.getMp3Infos(mainActivity);
        //mp3Infos=mainActivity.playService.mp3Infos;
        myMusicListAdapter = new MyMusicListAdapter(mainActivity, mp3Infos);
        listView_my_music.setAdapter(myMusicListAdapter);
    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        if (mainActivity.playService.getChangePlayList() != PlayService.MY_MUSIC_LIST) {
            mp3Infos = MediaUtils.getMp3Infos(mainActivity);//獲取Mp3列表
            mainActivity.playService.setMp3Infos(mp3Infos);
            mainActivity.playService.setChangePlayList(PlayService.MY_MUSIC_LIST);
        }
        this.listposition=position;
        mainActivity.playService.play(listposition);

        Mp3Info mp3Info = mp3Infos.get(position);
        System.out.println("本地列表 : " + mp3Info);
        //保存播放時間
        savePlayRecord();
    }

    //保存播放記錄
    private void savePlayRecord() {
        Mp3Info mp3Info = mainActivity.playService.getMp3Infos().get(mainActivity.playService.getCurrentPosition());
        try {
            Mp3Info playRecordMp3Info = mainActivity.app.dbUtils.findFirst(Selector.from(Mp3Info.class).where("mp3InfoId", "=", mp3Info.getId()));
            if (playRecordMp3Info == null) {
                mp3Info.setMp3InfoId(mp3Info.getId());
                mp3Info.setPlayTime(System.currentTimeMillis());//設置當前播放時間
                mainActivity.app.dbUtils.save(mp3Info);
            } else {
                playRecordMp3Info.setPlayTime(System.currentTimeMillis());
                mainActivity.app.dbUtils.update(playRecordMp3Info, "playTime");
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    //回調播放狀態下的UI設置
    public void changeUIStatusOnPlay(int position) {
        if (position >= 0 && position < mainActivity.playService.mp3Infos.size()) {
            Mp3Info mp3Info = mainActivity.playService.mp3Infos.get(position);
            textView_songName.setText(mp3Info.getTitle());
            textView2_singer.setText(mp3Info.getArtist());
            if (mainActivity.playService.isPlaying()) {
                imageView2_play_pause.setImageResource(R.mipmap.pause);
            } else {
                imageView2_play_pause.setImageResource(R.mipmap.play);
            }
            Bitmap albumBitmap = MediaUtils.getArtwork(mainActivity, mp3Info.getId(), mp3Info.getAlbumId(), true, true);
            imageView_album.setImageBitmap(albumBitmap);
            this.listposition = position;
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageView2_play_pause: {
                if (mainActivity.playService.isPlaying()) {
                    imageView2_play_pause.setImageResource(R.mipmap.player_btn_play_normal);
                    mainActivity.playService.pause();
                } else {
                    if (mainActivity.playService.isPause()) {
                        imageView2_play_pause.setImageResource(R.mipmap.player_btn_pause_normal);
                        mainActivity.playService.start();
                    } else {
                        mainActivity.playService.play(mainActivity.playService.getCurrentPosition());
                    }
                }
                break;
            }
            case R.id.imageView3_next: {
                mainActivity.playService.next();
                break;
            }
            case R.id.imageView_album: {
                Intent intent = new Intent(mainActivity, PlayActivity.class);
                startActivity(intent);
                break;
            }
            default:
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView parent, View view, int position, long id) {
        this.listposition = position;
        musicListItemDialog();
        return true;
    }

    /**
     * 自定義對話框
     */
    public void musicListItemDialog() {
        String[] menuItems = new String[]{"播放音樂", "設為鈴聲", "查看詳情","刪除音樂"};
        ListView menuList = new ListView(mainActivity);
        menuList.setCacheColorHint(Color.TRANSPARENT);
        menuList.setDividerHeight(1);
        menuList.setAdapter(new ArrayAdapter(mainActivity, R.layout.context_dialog_layout, R.id.dialogText, menuItems));
        menuList.setLayoutParams(new ViewGroup.LayoutParams(ConstantUtil
                .getScreen(mainActivity)[0] / 2, ViewGroup.LayoutParams.WRAP_CONTENT));

        final CustomDialog customDialog = new CustomDialog.Builder(mainActivity).setTitle(R.string.operation)
                .setView(menuList).create();
        customDialog.show();

        menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView parent, View view,
                                    int position, long id) {
                customDialog.cancel();
                customDialog.dismiss();
                if (position == 0) {
                    mainActivity.playService.play(listposition);
                } else if (position == 1) {
                    setRing();
                } else if (position == 2) {
                    showMusicInfo(listposition);
                } else if (position == 3) {
                    deleteMusic(listposition);
                }
            }

        });
    }

    private Mp3Info mp3Info = new Mp3Info();
    private void deleteMusic(int listposition) {
        mp3Info=mp3Infos.get(listposition);
        final String name = mp3Info.getDisplayName();
        final String url=mp3Info.getUrl();


        new CustomDialog.Builder(mainActivity)
                .setTitle(R.string.prompt)
                .setMessage("你確定徹底刪除“"+name+"”嗎?")
                .setPositiveButton(R.string.confrim,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                                dialog.dismiss();
                                File mf = new File(url);
                                if(mf.exists()){
                                    mf.delete();
                                    System.out.println(url);
                                    Toast.makeText(mainActivity, "已徹底成功刪除", Toast.LENGTH_LONG).show();
                                    SuccessListener listener =mainActivity;  // 回調接口
                                    listener.successListener(String.valueOf(mp3Infos.size())); // 回傳一個字符串 ,回傳什麼都行 ,只是告訴MainActivity ,已經下載成功了新的歌曲

                                    updateGallery(url);
                                }else {

                                    Toast.makeText(mainActivity, "該文件不存在", Toast.LENGTH_LONG).show();
                                }
                            }
                        }).setNeutralButton(R.string.cancel,null).show();
    }



    // 回調接口
    public interface SuccessListener {
        void successListener(String isSuccess); // 回傳一個字符串
    }

    /**
     * 通知媒體庫更新文件
     *
     */
    private void updateGallery(String filename)//filename是我們的文件全名,包括後綴哦
    {
        MediaScannerConnection.scanFile(mainActivity,
                new String[] { filename }, null,
                new MediaScannerConnection.OnScanCompletedListener() {
                    public void onScanCompleted(String path, Uri uri) {
                        Log.i("ExternalStorage", "Scanned " + path + ":");
                        Log.i("ExternalStorage", "-> uri=" + uri);
                    }
                });
    }

    /**
     * 設置鈴聲
     */
    protected void setRing() {
        RadioGroup rg_ring = new RadioGroup(mainActivity);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        rg_ring.setLayoutParams(params);
        // 第一個單選按鈕,來電鈴聲
        final RadioButton rbtn_ringtones = new RadioButton(mainActivity);
        rbtn_ringtones.setText("來電鈴聲");
        rbtn_ringtones.setTextColor(0xffffffff);
        rg_ring.addView(rbtn_ringtones, params);
        // 第二個單選按鈕,鬧鈴鈴聲
        final RadioButton rbtn_alarms = new RadioButton(mainActivity);
        rbtn_alarms.setText("鬧鈴鈴聲");
        rbtn_alarms.setTextColor(0xffffffff);
        rg_ring.addView(rbtn_alarms, params);
        // 第三個單選按鈕,通知鈴聲
        final RadioButton rbtn_notifications = new RadioButton(
                mainActivity);
        rbtn_notifications.setText("通知鈴聲");
        rbtn_notifications.setTextColor(0xffffffff);
        rg_ring.addView(rbtn_notifications, params);
        new CustomDialog.Builder(mainActivity).setTitle("設置鈴聲")
                .setView(rg_ring)
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                        dialog.dismiss();
                        if (rbtn_ringtones.isChecked()) {
                            try {
                                // 設置來電鈴聲
                                setRingtone(listposition);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if (rbtn_alarms.isChecked()) {
                            try {
                                // 設置鬧鈴
                                setAlarm(listposition);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if (rbtn_notifications.isChecked()) {
                            try {
                                // 設置通知鈴聲
                                setNotifaction(listposition);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).setNegativeButton("取消", null).show();
    }

    /**
     * 設置提示音
     *
     * @param position
     */
    protected void setNotifaction(int position) {
        Mp3Info mp3Info = mp3Infos.get(position);
        File sdfile = new File(mp3Info.getUrl().substring(4));
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, sdfile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, sdfile.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdfile
                .getAbsolutePath());
        Uri newUri = mainActivity.getContentResolver().insert(uri, values);
        RingtoneManager.setActualDefaultRingtoneUri(mainActivity,
                RingtoneManager.TYPE_NOTIFICATION, newUri);
        Toast.makeText(mainActivity, "設置通知鈴聲成功!", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 設置鬧鈴
     *
     * @param position
     */
    protected void setAlarm(int position) {
        Mp3Info mp3Info = mp3Infos.get(position);
        File sdfile = new File(mp3Info.getUrl().substring(4));
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, sdfile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, sdfile.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        values.put(MediaStore.Audio.Media.IS_ALARM, false);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdfile
                .getAbsolutePath());
        Uri newUri = mainActivity.getContentResolver().insert(uri, values);
        RingtoneManager.setActualDefaultRingtoneUri(mainActivity,
                RingtoneManager.TYPE_ALARM, newUri);
        Toast.makeText(mainActivity, "設置鬧鐘鈴聲成功!", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 設置來電鈴聲
     *
     * @param position
     */
    protected void setRingtone(int position) {
        Mp3Info mp3Info = mp3Infos.get(position);
        File sdfile = new File(mp3Info.getUrl().substring(4));
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DATA, sdfile.getAbsolutePath());
        values.put(MediaStore.MediaColumns.TITLE, sdfile.getName());
        values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
        values.put(MediaStore.Audio.Media.IS_RINGTONE, false);
        values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
        values.put(MediaStore.Audio.Media.IS_ALARM, true);
        values.put(MediaStore.Audio.Media.IS_MUSIC, false);

        Uri uri = MediaStore.Audio.Media.getContentUriForPath(sdfile
                .getAbsolutePath());
        Uri newUri = mainActivity.getContentResolver().insert(uri, values);
        RingtoneManager.setActualDefaultRingtoneUri(mainActivity,
                RingtoneManager.TYPE_RINGTONE, newUri);
        Toast.makeText(mainActivity, "設置來電鈴聲成功!", Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 顯示音樂詳細信息
     *
     * @param position
     */
    private void showMusicInfo(int position) {
        Mp3Info mp3Info = mp3Infos.get(position);
        LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(mainActivity.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.music_info_layout, null);
        ((TextView) view.findViewById(R.id.tv_song_title)).setText(mp3Info
                .getTitle());
        ((TextView) view.findViewById(R.id.tv_song_artist)).setText(mp3Info
                .getArtist());
        ((TextView) view.findViewById(R.id.tv_song_album)).setText(mp3Info
                .getAlbum());
        ((TextView) view.findViewById(R.id.tv_song_filepath)).setText(mp3Info
                .getUrl());
        ((TextView) view.findViewById(R.id.tv_song_duration)).setText(MediaUtils
                .formatTime(mp3Info.getDuration()));
        ((TextView) view.findViewById(R.id.tv_song_format)).setText(Constant
                .getSuffix(mp3Info.getDisplayName()));
        ((TextView) view.findViewById(R.id.tv_song_size)).setText(Constant
                .formatByteToMB(mp3Info.getSize()) + "MB");
        new CustomDialog.Builder(mainActivity).setTitle("歌曲詳細信息:")
                .setNeutralButton("確定", null).setView(view).create().show();
    }

}

my_music_list_layout.xml布局代碼





        


    

        
        

            
            
        

        
            
            

        
    


item_music_list.xml代碼如下



    

    

        
        
    

    

ConstantUtil.java代碼如下

package com.haoxue.zixueplayer.utils;

import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.WindowManager;

/**
 *  常量工具類
 * @author wwj
 *
 */
public class ConstantUtil {


	/**
	 * 獲取屏幕大小
	 * @param context
	 * @return
	 */
	public static int[] getScreen(Context context) {
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		Display display = windowManager.getDefaultDisplay();
		DisplayMetrics outMetrics = new DisplayMetrics();
		display.getMetrics(outMetrics);
		return new int[] {(int) (outMetrics.density * outMetrics.widthPixels),
				(int)(outMetrics.density * outMetrics.heightPixels)
		};
	}

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved