我这样开始Service
:
Intent intentService = new Intent(getActivity(), ACNotificationService.class);
intentService.putExtra("ACReservation", reservationActivity.acReservation);
getActivity().startService(intentService);
这是我的Service
课程:
/*
Variables
*/
private NotificationManager notificationManager;
private CountDownTimer countDownTimer;
private static int NOTIFICATION_COUNTDOWN = 0;
private static int NOTIFICATION_RANOUT = 1;
private ACReservation acReservation;
/*
Callbacks
*/
@Override
public void onCreate() {
super.onCreate();
// Initialize variables
notificationManager =
(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
// Register EventBus
EventBus.getDefault().register(this);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Get reservation data from extras
if (acReservation == null) {
acReservation = (ACReservation) intent.getExtras().get("ACReservation");
}
// Start timer
countDownTimer = new CountDownTimer(acReservation.getRemainingMilliseconds(), 100) {
@Override
public void onTick(long millisUntilFinished) {
// Update/Show notification
notificationManager.notify(NOTIFICATION_COUNTDOWN, createReservationActiveNotification((int)TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
}
@Override
public void onFinish() {
// Clear notifications
notificationManager.cancel(NOTIFICATION_COUNTDOWN);
// Stop service
stopSelf();
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
/*
Methods
*/
public Notification createReservationActiveNotification(int expInMinutes) {
Notification.Builder notification = new Notification.Builder(getApplicationContext());
notification.setContentTitle("Reservation");
notification.setContentText("Your reservation expires in " + expInMinutes + " minutes");
notification.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
notification.setSmallIcon(R.drawable.car_icon);
notification.setOngoing(true);
notification.setPriority(Notification.PRIORITY_MAX);
notification.setOnlyAlertOnce(true);
return notification.build();
}
public void onEvent(ACEventBusButtonClick buttonClick) {
if (buttonClick.getButtonAction() != null) {
if (buttonClick.getButtonAction().equals(ACEventBusButtonClick.BUTTON_CANCEL_RESERVATION)) {
notificationManager.cancel(NOTIFICATION_COUNTDOWN);
countDownTimer.cancel();
stopSelf();
}
}
}
这很简单。我将对象从Intent
中取出并用它来计算毫秒数。然后我开始新的CountDownTimer
,不断更新Notification
。
在系统重新启动Service
之前,它应该正常工作。它丢失了Intent
额外数据,并在重新启动时在此代码行崩溃:
if (acReservation == null) {
acReservation = (ACReservation) intent.getExtras().get("ACReservation");
}
日志说崩溃是因为Intent
是null
。所以当重新启动getExtras()
时,我在空对象上调用Service
。
我该如何解决这个问题?