gpt4 book ai didi

java - Android - 如何关闭由startForeground启动的服务中的通知?

转载 作者:行者123 更新时间:2023-12-01 15:49:17 24 4
gpt4 key购买 nike

假设我通过应用程序的服务中的以下内容启动通知:

notification = new Notification(R.drawable.icon, getText(R.string.app_name), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, mainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
initService.notification.setLatestEventInfo(this, getText(R.string.app_name), "ibike rider", pendingIntent);

startForeground(ONGOING_NOTIFICATION, notification);

我该如何关闭/取消此服务?是否可以在其他 Activity 中做到这一点?

谢谢。

最佳答案

任何“启动”服务(无论是后台服务还是前台服务)都可以通过 startService 调用启动,并通过 stopService 调用停止。

如果您的服务可以在其 onStartCommand 实现中处理多个请求,那么您可以通过额外调用 startService 来管理其生命周期:

public int onStartCommand(Intent intent, int flags, int startId) {
// ...

if (intent.getAction().equals(STOP_MY_SERVICE)) {
stopSelf();
return START_STICKY;
}

if (intent.getAction().equals(START_FOREGROUND)) {

// startForeground(...);

return START_STICKY;
}

if (intent.getAction().equals(STOP_FOREGROUND)) {
stopForeground(true);
return START_STICKY;
}

// ...
return START_STICKY;
}

有关示例,请参阅 LocationService.java - GTalkSMS

关于java - Android - 如何关闭由startForeground启动的服务中的通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6448730/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com