android - Intent 服务销毁后仍出现前台通知
问题描述
我有一个 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);
解决方案
完成这些工作后,您可以调用stopForeground(true)。这样您的服务就会立即从前台状态中删除,并且该参数true
确保将删除通知。
推荐阅读
- angular - 角度下拉引导问题 [autoClose]="'outside'" 不起作用
- reactjs - 使用 Semanti-Ui React 从组件“InputSelect”类型的字段中获取 ID
- c# - 无法在运行时在 .Net 5 中编译字符串
- c# - 如何使用方法 GetAll() 和 UnitOfWork(存储库模式)过滤数据
- javascript - 倒计时没有正确停止
- c++ - 如何正确导入和使用 CryptProtectData 方法
- node.js - Firebase 设置方法在填充之前擦除集合(使用 node.js)
- wordpress - WordPress WP_Query 仅显示总帖子的一部分
- android - React Native [0.66.1]:无法构建 android 和 ios 包
- sprite-kit - SKScene didMove(查看:SKView)在某些设备上被调用了两次(不在模拟器和其他设备中)