从IntentService迁移到Android O的JobIntentService

Kun*_*unu 3 android background-service android-8.0-oreo jobintentservice

以前,我使用IntentService定期将数据发送到服务器。但是,由于Android O限制了后台任务和进程,所以我正在转向JobIntentService。

我的活动代码以安排警报

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);
Run Code Online (Sandbox Code Playgroud)

我的服务如下

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

    @Override
    public void onCreate() {
        super.onCreate();
    }
}
Run Code Online (Sandbox Code Playgroud)

此代码的接收方是

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当应用程序在后台运行时,这不适用于Android O,如果我context.startForegroundService(myIntent);用来启动服务,则会抛出异常Context.startForegroundService() did not then call Service.startForeground()

Com*_*are 5

JobIntentService大部分是从UI调用的服务,例如执行大型下载的服务,该服务是由用户单击“下载!”启动的 按钮。

对于定期的背景工作,请使用JobSchedulerJobService。如果您需要支持低于Android 5.0的版本,请使用合适的包装器库(例如Evernote的android-job),该包装器库将JobScheduler在较新的设备和AlarmManager较旧的设备上使用。

或者,坚持使用AlarmManager,但使用前台服务。