用contentResolver+ListView+mediaPlayer实现简单Android音乐播放器

此类作为数据库查询结果bean

public class MusicBean {
    private String title;
    private String singer;
    private String path;
    private long time;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}

此类用来查询数据库和时间转换

public class MusicUtil {

    @RequiresApi(api = Build.VERSION_CODES.O)
    static public ArrayList<MusicBean> getAllMusic(Context context) {
        ArrayList<MusicBean> all = new ArrayList<>();

        ContentResolver contentResolver = context.getContentResolver();//获取ContentResolver对象
        //调用contentResolver对象的query方法查询系统表的音频文件数据
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null);
        //通过cursor取出查询数据存放在musicBean中
        while (cursor.moveToNext()) {
            MusicBean bean = new MusicBean();
            bean.setTitle(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
            bean.setSinger(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST)));
            bean.setPath(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA)));
            bean.setTime(cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION)));
            all.add(bean);
        }
        return all;
    }

    /*毫秒转化成分钟加秒*/
    public static String formatTime(long time) {
        String min = (time / (1000 * 60)) + "";//得到分钟
        String second = (time % (1000 * 60) / 1000) + "";//得到秒
        return min + "分" + second + "秒";
    }
}

此类是activity类,实现转化资源文件,动态申请权限,自定义ListView适配器,将bean中封装的数据更新到item中的数据项中显示出来

ublic class MainActivity extends AppCompatActivity {
    ListView listView;
    MediaPlayer mp;     //播放音频对象
    ArrayList<MusicBean> data;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = findViewById(R.id.lv);
        mp = new MediaPlayer();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            data = MusicUtil.getAllMusic(this);
            MyAdapter myAdapter = new MyAdapter();
            listView.setAdapter(myAdapter);
        } else {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 101);
        }
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mp.isPlaying()) {
                    mp.stop();
                } else {
                    mp.reset();
                    try {
                        mp.setDataSource(data.get(position).getPath());
                        mp.prepare();
                        mp.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        });
    }
/*权限申请结果回调方法*/
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 101 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            data = MusicUtil.getAllMusic(this);
            MyAdapter myAdapter = new MyAdapter();
            listView.setAdapter(myAdapter);
        } else {
            Toast.makeText(getApplicationContext(), "请授予权限否则无法使用", Toast.LENGTH_SHORT).show();
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
     /*自定义适配器*/
    class MyAdapter extends BaseAdapter {

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

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

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.item, null);
            MusicBean bean = data.get(position);
            TextView tv_title = view.findViewById(R.id.tv_title);
            TextView tv_singer = view.findViewById(R.id.tv_singer);
            TextView tv_time = view.findViewById(R.id.tv_time);
            TextView tv_path = view.findViewById(R.id.tv_path);
            tv_title.setText(bean.getTitle());
            TextPaint tp = tv_title.getPaint();//中文字体加粗
            tp.setFakeBoldText(true);
            tv_singer.setText(bean.getSinger());
            tv_time.setText(MusicUtil.formatTime(bean.getTime()));
            tv_path.setText(bean.getPath());
            if(position%2==0){ //改变背景颜色
                view.setBackgroundResource(R.drawable.item);
            }

            return view;
        }
    }
}

有一点要提一下,使用资源文件设置listView的背景颜色,在此分享给大家,在darwable资源目录下新建xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorAccent"></item>
    <item android:state_pressed="false" android:drawable="@color/coloritem"></item>
</selector>

其中true表示未长按时,false表示长按选中时

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
<TextView
    android:id="@+id/tv_title"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_singer"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_path"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>
    <TextView
        android:id="@+id/tv_time"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>


</LinearLayout>

用contentResolver+ListView+mediaPlayer实现简单Android音乐播放器

上一篇:生产者消费者问题(线程之间的协作)


下一篇:2020最新在线观影,视频解析平台,免费影视网站合集