【问题标题】:Migrating from IntentService to JobIntentService for Android O从 IntentService 迁移到 Android O 的 JobIntentService
【发布时间】:2018-07-26 02:06:35
【问题描述】:

以前我使用 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);

我的服务如下

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

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

此代码的接收者是

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);
    }
}

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

【问题讨论】:

  • 停止使用alarmmanager来安排非警报的任意任务。使用作业调度器
  • SDK 版本较低有解决办法吗?

标签: android background-service android-8.0-oreo jobintentservice


【解决方案1】:

JobIntentService 主要用于将从 UI 调用的服务,例如执行大量下载的服务,由用户单击“下载!”启动。按钮。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 2019-04-14
    • 2019-01-14
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多