Android OneTime IntentService 在应用程序被杀死时死亡

标签 android kotlin intentservice

我需要在 10 秒后运行任务,即使应用已关闭。我创建了 IntentService:

class SomeService: IntentService() {

    override fun onHandleIntent(intent: Intent?) {
        Thread.sleep(10_000)
        somefunction()
    }
}

Intent 服务在应用终止后终止。 我无法使用 BroadcastReceiver 重新启动它,因为它是一次性服务,必须在 10 秒后执行此操作

最佳答案

引用 Android 开发者指南

IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 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 不满意,我会很快用示例更新答案。

关于Android OneTime IntentService 在应用程序被杀死时死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51308483/

相关文章:

android - 在 Android 中通过 Intent 打开 Google Plus 页面

android - 如何在 Android 中禁用分段控制?

gradle - 理解 Gradle 是否需要 Groovy 知识?

android - Robolectric 和 IntentServices

java - 如何获取 hideSoftInputFromInputMethod(token, flags) 所需的 token ?

generics - 如何链接两个 Kotlin 函数参数的泛型类型?

kotlin - 是否可以在特定目录中禁止显示警告?

android - 从 IntentService 启动 Activity 在 Android 12 中不起作用

android - IntentService 连接到服务器监听

android - 复制 map 跟随 Android 中的当前位置功能