context.startService在Oreo上崩溃

时间:2018-07-27 06:42:20

标签: android broadcastreceiver android-8.0-oreo

我有一个Android应用,每30分钟获取一次位置数据。这是我注册广播接收器的方式。

    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction("com.example.partners.alarms");
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    Calendar time = Calendar.getInstance();
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
            time.getTimeInMillis(),
            1000 * 60 * 30, alarmIntent);

然后它像这样被调用:

public class AlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    context.startService(new Intent(context, AttendanceChecker.class));
    ((OperationsApplication)context.getApplicationContext()).getJobManager().start();
}

}

到目前为止,它一直运行良好,但是随着Android O崩溃。我在网上阅读了有关此内容的内容,但无法提出正确的解决方案。

编辑: startService()方法引发IllegalStateException

java.lang.RuntimeException: 
  at android.app.ActivityThread.handleReceiver (ActivityThread.java:3303)
  at android.app.ActivityThread.-wrap17 (Unknown Source)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1746)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:192)
  at android.app.ActivityThread.main (ActivityThread.java:6688)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:445)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:867)
Caused by: java.lang.IllegalStateException: 
  at android.app.ContextImpl.startServiceCommon (ContextImpl.java:1526)
  at android.app.ContextImpl.startService (ContextImpl.java:1482)
  at android.content.ContextWrapper.startService (ContextWrapper.java:650)
  at android.content.ContextWrapper.startService (ContextWrapper.java:650)
  at com.example.app.AlarmReceiver.onReceive (AlarmReceiver.java:11)

1 个答案:

答案 0 :(得分:1)

Android 8.0(API级别26)还包括对特定方法的以下更改:

如果面向Android 8.0的应用在不允许创建后台服务的情况下尝试使用该方法,则startService()方法现在将引发IllegalStateException。

新的Context.startForegroundService()方法将启动前台服务。系统允许应用程序在后台运行时调用Context.startForegroundService()。但是,应用程序必须在创建服务后五秒钟内调用该服务的startForeground()方法。阅读此内容,对您有帮助          https://developer.android.com/about/versions/oreo/android-8.0-changes