Reputation: 166
I need to run a task after 10 seconds, even if the app is closed. I created IntentService:
class SomeService: IntentService() {
override fun onHandleIntent(intent: Intent?) {
Thread.sleep(10_000)
somefunction()
}
}
Intent service dies after app dies. I can't relaunch it with BroadcastReceiver, because its one-time service, which must perform this action after 10 seconds
Upvotes: 1
Views: 132
Reputation: 903
Quoting Android Developer Guide
IntentService is subject to all the background execution limits imposed with Android 8.0 (API level 26)
You can read more about the restrictions here https://developer.android.com/about/versions/oreo/background
Some solutions you can try are
1)Have a foreground service (Attach a notification to the service)
In Java, the way I do is I have two utility methods created
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);
}
}
And in your service
@Override
protected void onHandleIntent(Intent intent) {
Utils.startNotificationAlongWithForegroundService(this,"channel_id","channelname","title","body",123);
//your work
Utils.destroyForegroundService(this);
}
2)Use JobService/Workmanager
I will update the answer with the examples on this shortly if you are not comfortable with using Job services/WorkManager.
Upvotes: 2