android - Android OneTime IntentService 在应用程序被杀死时死亡
问题描述
即使应用程序关闭,我也需要在 10 秒后运行任务。我创建了 IntentService:
class SomeService: IntentService() {
override fun onHandleIntent(intent: Intent?) {
Thread.sleep(10_000)
somefunction()
}
}
应用程序死亡后,意图服务死亡。我无法使用 BroadcastReceiver 重新启动它,因为它是一次性服务,必须在 10 秒后执行此操作
解决方案
引用 Android 开发者指南
IntentService 受 Android 8.0(API 级别 26)施加的所有后台执行限制的约束
您可以在此处阅读有关限制的更多信息https://developer.android.com/about/versions/oreo/background
您可以尝试的一些解决方案是
1)有前台服务(给服务附加通知)
在 Java 中,我的做法是创建了两个实用程序方法
public static void startNotificationAlongWithForegroundService(Service service,String CHANNEL_ID_FOREGROUND,String CHANNEL_NAME_FOREGROUND, String title, String body, Integer notification_id) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(service, CHANNEL_ID_FOREGROUND)
.setContentTitle(title)
.setContentText(body)
.setOngoing(true)
.setSmallIcon(R.drawable.ic_launcher)
.setProgress(100, 0, true);
NotificationManager mNotificationManager = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = mNotificationManager.getNotificationChannel(CHANNEL_ID_FOREGROUND);
if(channel==null) {
channel = new NotificationChannel(CHANNEL_ID_FOREGROUND,CHANNEL_NAME_FOREGROUND, NotificationManager.IMPORTANCE_NONE);
channel.setShowBadge(false);
if (mNotificationManager != null) {
mNotificationManager.createNotificationChannel(channel);
}
}
service.startForeground(notification_id, builder.build());
}
}
public static void destroyForegroundService(Service context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.stopForeground(true);
}
}
并为您服务
@Override
protected void onHandleIntent(Intent intent) {
Utils.startNotificationAlongWithForegroundService(this,"channel_id","channelname","title","body",123);
//your work
Utils.destroyForegroundService(this);
}
2)使用JobService/Workmanager
如果您对使用 Job services/WorkManager 不满意,我将很快用示例更新答案。
推荐阅读
- rest - 如何在 Rest API 中维护静态引用数据
- bash - 用于检查乘法结果并引发错误的 AWk 脚本
- postgresql - Postgresql - 准备好的语句与连接池 - 这是一种权衡吗?
- powershell - 检查 azure storage powershell 中是否存在表
- sap-fiori - Fiori中目录和目录组之间的区别
- typescript - 我如何扩展声明为命名空间的类
- javascript - ExtJs (v 6.0.0, classic) 带有自定义文本和表单的消息框
- javascript - JQuery parseXML 似乎什么也没给我
- node.js - 在路由中创建了一个 Promise,但未从其返回
- javascript - 无法使用 react-router 访问 URL 路径组件