实现点击通知栏发送广播控制音乐的播放、暂停、上一曲、下一曲

Intent intent = new Intent(this,Main2Activity.class);
        PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pending);
        builder.setOngoing(true);//设置左右滑动不能删除
        builder.setContent(remoteViews);

实现点击通知栏进入播放详情界面,Main2Activity就是播放详情界面,

        Intent intentPause = new Intent("play");//发送播放音乐的通知
        PendingIntent pIntentPause = PendingIntent.getBroadcast(this, 0,
                intentPause, 0);
        remoteViews.setOnClickPendingIntent(R.id.now, pIntentPause);
        Intent intentNext = new Intent("next");//发送播放下一曲的通知
        PendingIntent pIntentNext = PendingIntent.getBroadcast(this, 0,
                intentNext, 0);
        remoteViews.setOnClickPendingIntent(R.id.next, pIntentNext);

        Intent intentLast = new Intent("last");//发送播放上一曲的通知
        PendingIntent pIntentLast = PendingIntent.getBroadcast(this, 0,
                intentLast, 0);
        remoteViews.setOnClickPendingIntent(R.id.last, pIntentLast);

        Intent intentCancel = new Intent("cancel");//发送关闭通知栏的通知
        PendingIntent pIntentCancel = PendingIntent.getBroadcast(this, 0,
                intentCancel, 0);
        remoteViews
                .setOnClickPendingIntent(R.id.move, pIntentCancel);

使用intent的隐式意图定义广播,需要注意的是intent的action不能通过@String/xxx的形式设置,必须直接使用字符串声明,如"play",当点击相应的按钮时会发送对应的广播
那么就需要定义一个广播接收者,广播接收者的注册分为静态注册和动态注册两种方式,这是静态注册的方法,使用静态注册一旦注册成功那么receive就始终存在,
<receiverandroid:name=".receiver.AudioBecomingNoisyReceiver"><intent-filter><actionandroid:name="android.media.AUDIO_BECOMING_NOISY" />intent-filter>
我使用的是在服务中定义一个广播接收者,动态注册,这样他与服务的声明周期就相同了,同时也方便对服务进行歌曲的操作
先声明服务接受者
public class Receive extendsBroadcastReceiver{@Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(player!=null){
                if(action.equals("play")){

                    if(mState==State.PAUSED){

                        rePlaySong();
                    }elseif(mState==State.STOPPED){
                        Log.i("actioSTOPPEDn",action);

                        startPlaySong(mdata.get(POSITION));
                    }
                }elseif(action.equals("pause")){
                    pausePlaySong();
                }elseif(action.equals("next")){
                    startPlayNext();
                }elseif(action.equals("last")){
                    startPlayLast();
                }elseif(action.equals("cancel")){
                    //关闭通知栏
                    nm.cancel(9);
                }
            }
        }
动态注册:
Receive receive = new Receive();
IntentFilter filter = new IntentFilter(); filter.addAction( "play"); filter.addAction( "pause"); filter.addAction( "next"); filter.addAction( "last"); filter.addAction( "cancel"); registerReceiver(receive, filter);这样就完成了广播的发送,广播的接收,通过对通知栏的操作控制音乐的播放,


你可能感兴趣的:(实现点击通知栏发送广播控制音乐的播放、暂停、上一曲、下一曲)