我得到一個IntentService,它在onHandleIntent(Intent)內同步執行一些長時間運行的工作。所以,只要服務運行,我就會顯示通知。現在,我想在用戶點擊通知後停止服務。等待Intent從通知未收到
這就是我得到的。創建服務後註冊的廣播 - 接收機類。具有掛起意圖的通知,當服務執行某些工作時顯示。
但不知何故,當用戶點擊通知時,我從來沒有得到廣播意圖。任何想法?
以下是可輕鬆重新用於測試的部分代碼。
public class SyncService extends IntentService
{
private static final String TAG = SyncService.class.getSimpleName();
private static final int NOTIFICATION_REF_ID = 1;
private static final String ACTION_CANCEL = TAG + ".CANCEL";
private CancelReceiver receiver;
public SyncService() {
super(SyncService.class.getSimpleName());
}
private class CancelReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
stopSelf();
}
}
@Override
public void onCreate() {
super.onCreate();
receiver = new CancelReceiver();
IntentFilter filter = new IntentFilter(ACTION_CANCEL);
registerReceiver(receiver, filter);
}
@Override
public void onDestroy() {
super.onDestroy();
if (receiver != null)
unregisterReceiver(receiver);
}
@Override
protected void onHandleIntent(Intent intent) {
Intent cancelIntent = new Intent(this, CancelReceiver.class);
cancelIntent.setAction(ACTION_CANCEL);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
cancelIntent, 0);
// create notification and set pending-intent
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("some caption")
.setContentText("some hint")
.setTicker("some caption").setSmallIcon(R.drawable.ic_action_refresh)
.setOngoing(true).setWhen(System.currentTimeMillis())
.setContentIntent(pendingIntent).setProgress(0, 0, true);
Notification notification;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
notification = builder.getNotification();
else
notification = builder.build();
// show notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(SyncService.class.getCanonicalName(), NOTIFICATION_REF_ID,
notification);
// now do some long running work synchronously
// cancel/remove notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(SyncService.class.getCanonicalName(), NOTIFICATION_REF_ID);
}
}
的服務是從我的活動中開始:
Intent syncIntent = new Intent(this, SyncService.class);
startService(syncIntent);
的想法停止服務一樣,來自this post。
請勿使用兩個通知管理器。 – greenapps
如果用戶點擊通知,它會消失嗎? – greenapps
IntentService在完成其onHandleIntent()工作後會自動調用stopSelf()。我想知道如果onDestroy()在它有機會播出之前註銷您的接收器。我會在每個生命週期方法中放置一些日誌語句以確認事物被調用的順序。 –