在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中与以前相比有所不同?