在Oreo及更高版本中关闭应用程序时触发AlarmManager

时间:2018-12-28 18:23:33

标签: android android-service alarmmanager android-broadcastreceiver

在Android 7.1(Lollipop)中使用AlarmManager并放下并关闭应用程序时,将执行带有PendingIntent的{​​{1}}和带有Service的{​​{1}}。在Android 8(Oreo)和更高版本中,关闭应用程序后仅执行BroadcastReceivers。

这里是一个例子:

活动

BroadcastReceiver

服务

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        long currentTimeMillis = System.currentTimeMillis();
        for (long i = currentTimeMillis; i < currentTimeMillis + 60000; i += 10000) {
            Intent serviceIntent = new Intent(getApplicationContext(), TestService.class);
            PendingIntent servicePendingIntent = PendingIntent.getService(getApplicationContext(), (int) i, serviceIntent, PendingIntent.FLAG_ONE_SHOT);

            Intent receiverIntent = new Intent(getApplicationContext(), TestReceiver.class);
            PendingIntent receiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) i, receiverIntent, PendingIntent.FLAG_ONE_SHOT);

            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, i, servicePendingIntent);
            alarmManager.set(AlarmManager.RTC_WAKEUP, i, receiverPendingIntent);
        }
    }
}

接收器

public class TestService extends IntentService {
    public TestService() {
        super("TestService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        System.out.println("Service");
    }
}

清单

public class TestReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Receiver");
    }
}

在Lollipop上执行此操作时,所有操作均符合预期:

<service android:name=".TestService" />
<receiver android:name=".TestReceiver" />

在奥利奥,发生这种情况:

I/System.out: Receiver
I/System.out: Service
I/System.out: Receiver
I/System.out: Service
I/System.out: Receiver
I/System.out: Service
*App closed here*
I/System.out: Receiver
I/System.out: Service
I/System.out: Service
I/System.out: Receiver
I/System.out: Receiver
I/System.out: Service

为什么I/System.out: Service I/System.out: Receiver I/System.out: Service I/System.out: Receiver *App closed here* I/System.out: Receiver I/System.out: Receiver I/System.out: Receiver I/System.out: Receiver 使用AlarmManager的行为在Oreo中与以前相比有所不同?

1 个答案:

答案 0 :(得分:0)

Android Oreo限制了创建后台服务的能力。有关更多信息,请参见here。您将必须使用JobIntentService或类似工具围绕它进行编码。