【发布时间】:2016-11-12 00:13:30
【问题描述】:
我创建了一个服务,以便我可以有一个持久的通知。我希望此通知有一个选项,可以将意图发送到我的另一个活动。
该选项本质上会在应用程序生成的每个进程中停止。因此,一旦按下操作,通知也需要关闭。
我正在尝试使用待处理的广播意图来完成此操作,但由于某种原因,广播接收器没有捕捉到该意图。我在服务的 onCreate() 方法中动态注册接收器,并在服务的 onDestroy() 方法中取消注册。
public class myService extends IntentService {
private boolean shown = false;
private ButtonReceiver buttonReceiver;
//Side note: this is legacy code. Necessary?
public myService() {
super("myService");
}
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter("com.myapp.KILL_NOTIFICATION");
this.buttonReceiver = new ButtonReceiver();
this.registerReceiver(this.buttonReceiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(this.buttonReceiver);
}
@Override
protected void onHandleIntent(Intent intent) {
if(intent.getAction() == "com.myapp.START_SERVICE") {
//generate a unique id for the notification
int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.US).format(new Date()));
//create a pending intent to send off when the kill action is pressed
Intent buttonIntent = new Intent("com.myapp.KILL_NOTIFICATION");
buttonIntent.putExtra("notificationId", id);
PendingIntent btPendingIntent = PendingIntent.getBroadcast(this, 0, buttonIntent, 0);
Notification.Builder builder = new Notification.Builder(getApplicationContext());
builder.setAutoCancel(false);
builder.setContentTitle("my app");
//builder.setContentText("Press this notification to kill.");
builder.setOngoing(true);
builder.setSmallIcon(R.drawable.ic_launcher);
//builder.setContentIntent(pendingIntent);
builder.addAction(R.drawable.ic_clear_black_24dp, "Kill my app", btPendingIntent);
builder.setWhen(0);
builder.setPriority(Notification.PRIORITY_MAX);
Notification notification = builder.build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//TODO need to find first unused notif id
notificationManager.notify(id, notification);
}
}
public class ButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("notificationId", 0);
Intent killIntent = new Intent("com.myapp.KILL_EVERYTHING");
killIntent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(killIntent);
//cancel notification
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(notificationId);
}
}
}
【问题讨论】:
标签: android android-intent android-broadcastreceiver