Migrating from IntentService to JobIntentService for Android O
Asked Answered
R

1

6

Previously I was using IntentService to send data to the server periodically. However, since Android O limiting background task and processes I am moving towards JobIntentService.

My Activity code to schedule an alarm

Intent intent = new Intent(BaseActivity.this, EventBroadcastReceiver.class);

// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, EventBroadcastReceiver.REQUEST_CODE,
        intent, PendingIntent.FLAG_UPDATE_CURRENT);

// Setup periodic alarm every half hour
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
        AlarmManager.INTERVAL_HALF_HOUR, pIntent);

And my Service is as follows

public class EventAnalyticsService extends JobIntentService {    
    @Override
    protected void onHandleWork(@NonNull Intent intent) {
        // Perform your task
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
}

Receiver for this code is

public class EventBroadcastReceiver extends BroadcastReceiver {

    public static final int REQUEST_CODE = 12345;

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent myIntent = new Intent(context, EventAnalyticsService.class);
        context.startService(myIntent);
    }
}

However this is not working for Android O when app is in background and if I use context.startForegroundService(myIntent); to start my service it is throwing exception as Context.startForegroundService() did not then call Service.startForeground()

Ricercar answered 15/2, 2018 at 10:38 Comment(2)
stop using alarmmanager to schedule arbitrary tasks that are not alarms. Use jobschedulerMeed
Is there any workaround for lower SDK version?Ricercar
O
5

JobIntentService is there mostly for a service that will be invoked from the UI, such as a service to perform a large download, initiated by the user clicking a "Download!" button.

For periodic background work, use JobScheduler and a JobService. If you need to support older than Android 5.0, use a suitable wrapper library (e.g., Evernote's android-job), one that will use JobScheduler on newer devices and AlarmManager on older devices.

Alternatively, stick with AlarmManager, but use a foreground service.

Oestrin answered 15/2, 2018 at 11:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.