我创建了一个活动,该活动根据用户输入值(小时、分钟)启动警报,这些值在同一活动中使用 SharedPreferences 保存。我想要做的是在手机重启后启动该警报,但我需要使用活动中的 SharedPreferences 将这些值保存到 BroadcastReceiver 中,该广播接收器在 BOOT_COMPLETED 操作上进行过滤。我试图这样做,但我得到的是默认值“0”:
package com.salivan.calmmanager;
import java.util.Calendar;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
public class AlarmReceiverBC extends BroadcastReceiver {
int hour = 0;
int min = 0;
public AlarmReceiverBC() {
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
SharedPreferences savedData = context.getSharedPreferences("PREFS_SAVED_DATA", Context.MODE_PRIVATE); //here I try to get
//the SharedPreferences but I think that the context object is wrong because it's sent by system and not by the activity where my values are...
Calendar calendar = Calendar.getInstance();
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
this.hour = savedData.getInt("HOUR", 0);
this.min = savedData.getInt("MIN", 0);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, this.hour);
calendar.set(Calendar.MINUTE, this.min);
calendar.set(Calendar.SECOND, 0);
Intent intentForReceiver = new Intent(context, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intentForReceiver, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, alarmIntent);
}
}
}