java在重新启动后缺少意图“extras”值
我刚刚发现,我不知道如何在设备重新启动后保存我的意向附加。我需要它来通知日程安排
这里是我设置报警的main活动的一部分
Calendar startTime = Calendar.getInstance();
startTime.set(Calendar.HOUR_OF_DAY, hourOfDay);
startTime.set(Calendar.MINUTE, minute);
startTime.set(Calendar.SECOND, 0);
long alarmStartTime = startTime.getTimeInMillis();
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("notificationId", notificationId);
intent.putExtra("text", text);
intent.putExtra("alarmStartTime", alarmStartTime);
intent.setAction("安卓.intent.action.BOOT_COMPLETED");
intent.setAction("安卓.intent.action.QUICKBOOT_POWERON");
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, notificationId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, alarmStartTime, AlarmManager.INTERVAL_DAY, alarmIntent);
报警接收器
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null){
int notificationId = extras.getInt("notificationId");
String message = extras.getString("text");
String action = intent.getAction();
if (BOOT_COMPLETED.equals(action) ||
QUICKBOOT_POWERON.equals(action)) {
Intent service = new Intent(context, BootService.class);
service.setAction(message);
service.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
service.putExtra("notificationId", notificationId);
service.putExtra("text", message);
context.startService(service);
}
}
}
方法从BootService获取notificationId和消息
private void setAlarm(int Id, String message) {
Context context = MyApp.getContext();
Intent mainIntent = new Intent(context, MainActivity.class);
mainIntent.setAction("安卓.intent.action.BOOT_COMPLETED");
mainIntent.setAction("安卓.intent.action.QUICKBOOT_POWERON");
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager myNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(安卓.R.drawable.ic_dialog_info)
.setContentTitle("Wake up! " + Id)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setContentIntent(contentIntent);
myNotificationManager.notify(Id, builder.build());
}
@Override
protected void onHandleIntent(Intent intent) {
int Id = intent.getExtras().getInt("notificationId", 0);
String message = intent.getExtras().getString("text");
setAlarm(Id, message);
Context context = MyApp.getContext();
Intent service = new Intent(context, BootService.class);
stopService(service);
}
一切正常,但重新启动后,我的附加值为空。谢谢
# 1 楼答案
如果需要永久保存某些数据,可以创建一个包含所有额外值的HasMap
每次更新某些值时,您都可以序列化此映射,并将其保存在一个即使在重新启动后也始终可用的文件中
序列化并保存
最后,当您在重新启动后首次运行应用程序时,您将在地图上关联存储在序列化文件中的对象
还原Hasmap