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