我有一个ForegroundService,它是从BroadcastRevicer开始的,就像这样:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("WHD", "Alarm fired!");
Intent i = new Intent(context, RefreshIntentService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(i);
} else {
context.startService(i);
}
}
}
RefreshIntentService的onCreate如下:
@Override
public void onCreate() {
super.onCreate();
createRefreshNotificationChannel();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "notifications_refresh");
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setContentTitle(getResources().getString(R.string.app_name));
mBuilder.setPriority(Notification.PRIORITY_MIN);
mBuilder.setContentText("Refreshing...");
startForeground(1,mBuilder.build());
}
我现在在服务内部创建其他通知:
private void showNotification(Offer offer) {
createMainNotificationChannel();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "notifications");
mBuilder.setSmallIcon(R.drawable.ic_notification);
mBuilder.setLargeIcon(offer.getBitmap());
mBuilder.setContentTitle(offer.getName());
mBuilder.setContentText(getResources().getString(R.string.main_product_available_now) + " " + offer.getPrice());
mBuilder.setDefaults(Notification.DEFAULT_SOUND);
Intent i = new Intent(this, OfferDetailsActivity.class);
i.putExtra("ASIN", offer.getASIN());
PendingIntent p = PendingIntent.getActivity(this, (int)(Math.random() * 999999), i, PendingIntent.FLAG_CANCEL_CURRENT);
mBuilder.setContentIntent(p);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(offer.getASIN().hashCode(), mBuilder.build());
}
当服务终止时,Android会自动取消所有在服务内部创建的通知。我该如何预防?