private void initRemoteViews() {
remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);
//通知栏控制器上一首按钮广播操作
Intent intentPrev = new Intent(PREV);
PendingIntent prevPendingIntent = PendingIntent.getBroadcast(this, 0, intentPrev, 0);
//为prev控件注册事件
remoteViews.setOnClickPendingIntent(R.id.btn_notification_previous, prevPendingIntent);
//通知栏控制器播放暂停按钮广播操作 //用于接收广播时过滤意图信息
Intent intentPlay = new Intent(PLAY);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 0, intentPlay, 0);
//为play控件注册事件
remoteViews.setOnClickPendingIntent(R.id.btn_notification_play, playPendingIntent);
//通知栏控制器下一首按钮广播操作
Intent intentNext = new Intent(NEXT);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 0, intentNext, 0);
//为next控件注册事件
remoteViews.setOnClickPendingIntent(R.id.btn_notification_next, nextPendingIntent);
//通知栏控制器关闭按钮广播操作
Intent intentClose = new Intent(CLOSE);
PendingIntent closePendingIntent = PendingIntent.getBroadcast(this, 0, intentClose, 0);
//为close控件注册事件
remoteViews.setOnClickPendingIntent(R.id.btn_notification_close, closePendingIntent);
}
目前通知栏上看到的按钮只有四个,因为播放和暂停是一个按钮,到时候可以根据MediaPlayer的播放状态做进一步的处理,上面四个按钮,点击之后会发送一个广播,既然有广播,那自然要有一个广播接收器,就好比,你到淘宝上买衣服,别人给你发货了,你总要设置一个收货地址吧。这是一个道理的。至于广播接收器,可以写在Service里面,作为一个内部类使用。那么先创建这个内部类。
/**
- 广播接收器 (内部类)
*/
public class MusicReceiver extends BroadcastReceiver {
public static final String TAG = “MusicReceiver”;
@Override
public void onReceive(Context context, Intent intent) {
//UI控制
UIControl(intent.getAction(), TAG);
}
}
然后来看看UIControl方法。
/**
-
页面的UI 控制 ,通过服务来控制页面和通知栏的UI
-
@param state 状态码
-
@param tag
*/
private void UIControl(String state, String tag) {
switch (state) {
case PLAY:
BLog.d(tag,PLAY+" or "+PAUSE);
break;
case PREV:
BLog.d(tag,PREV);
break;
case NEXT:
BLog.d(tag,NEXT);
break;
case CLOSE:
BLog.d(tag,CLOSE);
break;
default:
break;
}
}
对应四个通知栏的按钮,这是是作为广播的接收。但是要实际收到,还要注册才行。
所以要注册动态广播。
/**
- 注册动态广播
*/
private void registerMusicReceiver() {
musicReceiver = new MusicReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(PLAY);
intentFilter.addAction(PREV);
intentFilter.addAction(NEXT);
intentFilter.addAction(CLOSE);
registerReceiver(musicReceiver, intentFilter);
}
在这里你可以发现,我对四个值进行了拦截过滤,也就是说当我点击通知栏的上一曲按钮时,会发送动作名为PREV的广播,而这个时候MusicReceiver拦截到PREV的广播,传递给onReceive。然后在onReceive对不同的动作做不同的处理,目前我只是打印了日志而已。
现在你可以将showNotification方法中的如下代码删除掉。
RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification);
然后在Service中的onCreate中调用。
@Override
public void onCreate() {
super.onCreate();
initRemoteViews();
//注册动态广播
registerMusicReceiver();
showNotification();
BLog.d(TAG, “onCreate”);
}
initRemoteViews