使用MediaPlayer+Service+Broadcast完成音乐播放器
1,封装歌曲的类
public class Song {
private String singer;
private String song;
private String path;
private int duration;
private long size;
private int position;
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public String getSong() {
return song;
}
public void setSong(String song) {
this.song = song;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
### 2 读取所有的歌曲
public class MusicUtils {
private static final String TAG = "hellow";
public static List<Song> getMusicData(Context context){
List<Song> list=new ArrayList<>();
int i=0;
Cursor cursor=context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,null,null,null,null);
Log.i(TAG, "getMusicData: "+MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
if(cursor!=null){
while (cursor.moveToNext()){
Song song=new Song();
song.getSong(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
song.getSinger(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)));
song.getPath(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)));
song.getDuration(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)));
song.getSize(cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE)));
song.getPosition(i);
i++;
list.add(song);
}
cursor.close();
}else{
Toast.makeText(context,"找不不到文件",Toast.LENGTH_SHORT).show();
Log.i(TAG, "getMusicData: no");
}
return list;
}
public static String formatTime(int time){
if(time/1000%60<110){
return time/1000/60+":0"+time/1000%60;
}else{
return time/1000/60+":"+time/1000%60;
}
}
}
3 创建listview布局适配器
public class MyAdapter extends BaseAdapter {
private Context context;
private List<Song> list;
private int flag=0;
public MyAdapter(Context context, List<Song> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if(convertView==null){
holder=new ViewHolder();
convertView=View.inflate(context,R.layout.list,null);
holder.song=convertView.findViewById(R.id.text1);
holder.singer=convertView.findViewById(R.id.text2);
holder.duration=convertView.findViewById(R.id.text3);
holder.position=convertView.findViewById(R.id.text4);
convertView.setTag(holder);
}else {
holder=(ViewHolder)convertView.getTag();
}
String song = list.get(position).getSong();
if(song.length()>=5&&song.substring(song.length()-4,song.length()).equals(".mp3")){
holder.song.setText(song.substring(0,song.length()-4).trim());
}else{
holder.song.setText(song.trim());
}
holder.singer.setText(list.get(position).getSinger().toString().trim());
int duration = list.get(position).getDuration();
String time = MusicUtils.formatTime(duration);
holder.duration.setText(time);
return convertView;
}
class ViewHolder{
TextView song,singer,duration,position;
}
}
4 service中的代码
public class MyServices extends Service {
private MediaPlayer mediaPlayer;
private Notification.Builder builder;
private List<Song> list;
private int index;
public MyServices() {
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer=new MediaPlayer();
list=MusicUtils.getMusicData(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationManager manager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
builder=new Notification.Builder(this);
builder.setSmallIcon(R.mipmap.ic_launcher);
RemoteViews views=new RemoteViews(getPackageName(),R.layout.tongzhi);
Intent intent1=new Intent();
intent1.setAction("com.notify.pause");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,100,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.pause,pendingIntent);
Intent intent2=new Intent();
intent2.setAction("com.notify.restart");
PendingIntent pendingIntent1=PendingIntent.getBroadcast(this,101,intent2,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.restart,pendingIntent1);
Intent intent3=new Intent();
intent3.setAction("com.notify.nav");
PendingIntent pendingIntent2=PendingIntent.getBroadcast(this,102,intent3,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.nav,pendingIntent2);
Intent intent4=new Intent();
intent4.setAction("com.notify.next");
PendingIntent pendingIntent3=pendingIntent.getBroadcast(this,103,intent4,PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.next,pendingIntent3);
builder.setCustomContentView(views);
startForeground(1,builder.build());
return super.onStartCommand(intent, flags, startId);
}
public class MusicBinder extends Binder{
public void callPlay(int position){
playSong(position);
}
public void callPause(){
pause();
}
//下一首
public void callPlayNextSong(){
PlayNextSong();
}
//上一首
public void callPlayNavSong(){
playNavSong();
}
public void callRestart(){
restart();
}
}
private void restart() {
mediaPlayer.start();
}
private void playNavSong() {
if(--index<0){
index=0;
}
playSong(index);
}
private void PlayNextSong() {
if(++index>list.size()-1){
index=0;
}
playSong(index);
}
private void pause() {
if(mediaPlayer.isPlaying()){
mediaPlayer.start();
}
}
private void playSong(int position) {
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
mediaPlayer.reset();
Song song=list.get(position);
try {
mediaPlayer.setDataSource(song.getPath());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
return new MusicBinder();
}
public void updateNotification(){
}
}
5 service中通知的布局文件
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageButton
android:id="@+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="@android:drawable/ic_media_pause" />
<ImageButton
android:id="@+id/restart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="@android:drawable/ic_media_play" />
<ImageButton
android:id="@+id/nav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="@android:drawable/ic_media_previous" />
<ImageButton
android:id="@+id/next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
app:srcCompat="@android:drawable/ic_media_next" />
</LinearLayout>
6 广播的内容
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "hellow";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "onReceive: "+action);
if(action.equals("com.notify.pause")){
MainActivity.handler.sendEmptyMessage(110);
}else if(action.equals("com.notify.restart")){
MainActivity.handler.sendEmptyMessage(120);
}else if(action.equals("com.notify.nav")){
MainActivity.handler.sendEmptyMessage(130);
}else if(action.equals("com.notify.next")){
MainActivity.handler.sendEmptyMessage(140);
}
}
}
7 MainActivity中的代码
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "11111111";
private ImageButton imageButton1;
private ImageButton imageButton2;
private ImageButton imageButton4;
private SeekBar seekBar;
private ListView listView;
private MediaPlayer mediaPlayer;
private Song song;
private List<Song> list;
private int index;
private ServiceConnection serviceConnection;
private static final String TAG = "MainActivity";
private ListView lv;
private Button pause;
private Button restart;
private Button nav;
private Button next;
private Song song;
private List<Song> listSong;
private int index;
private ServiceConnection connection;
public static Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG, "handleMessage:"+msg.what);
if(msg.what == 110){
binder.callPause();
}else if(msg.what == 120){
binder.callRestart();
}else if(msg.what == 130){
binder.callPlayNavSong();
}else if(msg.what == 140){
binder.callPlayNextSong();
}
}
};
public static MusicService.MusicBinder binder;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.notify.pause");
intentFilter.addAction("com.notify.restart");
intentFilter.addAction("com.notify.next");
intentFilter.addAction("com.notify.nav");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver,intentFilter);
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i(TAG, "onItemClick: ");
binder.callPlay(position);
index = position;
}
});
//启动服务
Intent intent = new Intent(this, MusicService.class);
startService(intent);
connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
binder = (MusicService.MusicBinder)(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
//绑定服务
bindService(intent,connection, Service.BIND_AUTO_CREATE);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.pause:
binder.callPause();
break;
case R.id.restart:
binder.callRestart();
break;
case R.id.nav:
binder.callPlayNavSong();
break;
case R.id.next:
if(++index > listSong.size() - 1){
index = 0;
}
binder.callPlayNextSong();
break;
}
}
private void initView() {
lv = findViewById(R.id.lv);
pause = findViewById(R.id.pause);
pause.setOnClickListener(this);
restart = findViewById(R.id.restart);
restart.setOnClickListener(this);
nav = findViewById(R.id.nav);
nav.setOnClickListener(this);
next = findViewById(R.id.next);
next.setOnClickListener(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
initAdapter();
}else{
finish();
}
}
//初始化适配器
public void initAdapter(){
listSong = MusicUtils.getMusicData(this);
MyAdapter myAdapter = new MyAdapter(this, listSong);
lv.setAdapter(myAdapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (connection != null){
unbindService(connection);
}
}
}
5 MainActivity中的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
<LinearLayout
android:id="@+id/line"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true">
<ImageButton
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="privice"
app:srcCompat="@android:drawable/ic_media_previous" />
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="stop"
app:srcCompat="@android:drawable/ic_media_pause" />
<ImageButton
android:id="@+id/imageButton4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:onClick="next"
app:srcCompat="@android:drawable/ic_media_next" />
</LinearLayout>
<LinearLayout
android:id="@+id/line2"
android:layout_above="@id/line"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/line2"></ListView>
</RelativeLayout>
9 listView的布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="歌名"
android:textSize="25sp"/>
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="歌手"
android:layout_below="@id/text1"
android:layout_marginTop="10dp" />
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="时间"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/text2"/>
<TextView
android:id="@+id/text4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="序号"
android:layout_alignParentRight="true"/>
</RelativeLayout>
10 清单文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wo_shi_shei_wo_zai_na_er">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"></receiver>
<service android:name=".MyServices"
android:enabled="true"
android:exported="true">
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>