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()