应用被杀死时,Android OneTime IntentService死亡

时间:2018-07-12 14:38:29

标签: android kotlin intentservice

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

class SomeService: IntentService() {

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

应用程序死亡后,意图服务死亡。 我无法使用BroadcastReceiver重新启动它,因为它的一次性服务必须在10秒后执行此操作

1 个答案:

答案 0 :(得分:2)

引用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,我将在此不久通过示例更新答案。