我有一个IntentService,在onCreate
中调用方法startforeground()
,然后在创建IntentService时看到通知。但是,当IntentService被销毁(转到onDestroy)时,我可以在销毁服务后的几秒钟内看到通知。这是为什么?
这是IntentService的代码:
public class USFIntentService extends IntentService {
private static final String TAG = "USFIntentService";
private static final int USF_NOTIFICATION_ID = 262276;
private static final String USF_NOTIFICATION_CHANNEL_ID = "USF_NOTIFICATION_CHANNEL";
public USFIntentService() {
super("USFIntentService");
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG,"in onCreate");
startUsfForegroundService();
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"in onDestroy");
}
private void startUsfForegroundService() {
// Define notification channel
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel =
new NotificationChannel(USF_NOTIFICATION_CHANNEL_ID, name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
// Build notification to be used for the foreground service.
Notification notification =
new Notification.Builder(this, USF_NOTIFICATION_CHANNEL_ID)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.usf_notification_icon)
.build();
// Set the service as a foreground service.
startForeground(USF_NOTIFICATION_ID, notification);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "onHandleIntent");
if (intent != null) {
doStuff();
}
Log.i(TAG,"End of onHandleIntent");
}
}
我这样称呼这项服务:
Intent startServiceIntent = new Intent(intent);
startServiceIntent.setComponent(new ComponentName(context, USFIntentService.class));
context.startForegroundService(startServiceIntent);
3条答案
按热度按时间rt4zxlrg1#
尝试在完成删除工作后调用
Service#stopForeground
k2fxgqgv2#
你可以在完成这些操作后调用stopForeground(true),这样你的服务就可以立即从前台状态中移除,参数
true
确保通知将被移除。jxct1oxe3#
如果提供了STOP_FOREGROUND_REMOVE,则服务的关联通知将立即取消。
如果提供了STOP_FOREGROUND_DETACH,则服务与通知的关联将被切断。如果由于前台服务通知延迟策略而尚未显示通知,则在调用stopForeground(STOP_FOREGROUND_DETACH)时会立即发布通知。在所有情况下,即使完全停止并销毁此服务,通知仍会显示。