使用 BroadcastReciever 我们可以连续运行后台服务,但是如果它会被杀死,会自动销毁重新实例化旧的服务实例
当服务强制停止时,它将调用 onDestroy() 方法,在这种情况下,当服务销毁并再次重新启动服务时,使用一个接收器并发送一个广播。在你下面的方法 com.android.app 是扩展广播接收器的接收器类的自定义操作
public void onDestroy() {
try {
myTimer.cancel();
timerTask.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent = new Intent("com.android.app");
intent.putExtra("valueone", "tostoreagain");
sendBroadcast(intent);
}
在 onReceive 方法中
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Service Stoped", "call service again");
context.startService(new Intent(context, ServiceCheckWork.class));
}
如果设备重新启动,那么我们有 onBootCompleted 动作让接收器捕捉
当你的目标是 SdkVersion "O"
在 MainActivity.java 中定义 getPendingIntent()
private PendingIntent getPendingIntent() {
Intent intent = new Intent(this, YourBroadcastReceiver.class);
intent.setAction(YourBroadcastReceiver.ACTION_PROCESS_UPDATES);
return PendingIntent.getBroadcast(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
这里我们将 PendingIntent 与 BroadcastReceiver 一起使用,并且此 BroadcastReceiver 已在 AndroidManifest.xml 中定义。
现在在包含 onReceive() 方法的 YourBroadcastReceiver.java 类中:
Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_PROCESS_UPDATES.equals(action)) {
NotificationResult result = NotificationResult.extractResult(intent);
if (result != null) {
List<Notification> notifications = result.getNotification();
NotificationResultHelper notificationResultHelper = new
NotificationResultHelper(
context, notifications);
// Save the notification data to SharedPreferences.
notificationResultHelper.saveResults();
// Show notification with the notification data.
notificationResultHelper.showNotification();
Log.i(TAG,
NotificationResultHelper.getSavedNotificationResult(context));
}
}
}
}