Android自定义Notification添加点击事件-创新互联
前言

在上一篇文章中《Notification自定义界面》中我们实现了自定义的界面,那么我们该怎么为自定义的界面添加点击事件呢?像酷狗在通知栏 有“上一首”,“下一首”等控制按钮,我们需要对按钮的点击事件进行响应,不过方法和之前的点击设置不一样,需要另外处理,下面我将进行简单的说明。
实现
同样,我们需要一个Service的子类MyService,然后在MyService的onCreate中设置,如下代码:
public class MyService extends Service {
public static final String ONCLICK = "com.app.onclick";
private BroadcastReceiver receiver_onclick = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ONCLICK)) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
}
}
};
@Override
public void onCreate() {
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
"JcMan", System.currentTimeMillis());
RemoteViews view = new RemoteViews(getPackageName(),R.layout.notification);
notification.contentView = view;
IntentFilter filter_click = new IntentFilter();
filter_click.addAction(ONCLICK);
//注册广播
registerReceiver(receiver_onclick, filter_click);
Intent Intent_pre = new Intent(ONCLICK);
//得到PendingIntent
PendingIntent pendIntent_click = PendingIntent.getBroadcast(this, 0, Intent_pre, 0);
//设置监听
notification.contentView.setOnClickPendingIntent(R.id.btn,pendIntent_click);
//前台运行
startForeground(1, notification);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
本文标题:Android自定义Notification添加点击事件-创新互联
URL分享:http://www.jxjierui.cn/article/iccgc.html


咨询
建站咨询
