重启后无法从Activity到BroadcastReceiver获取SharedPreferences

时间:2013-11-08 15:49:39

标签: android variables broadcastreceiver sharedpreferences

我创建了一个活动,根据用户输入值(小时,分钟)启动报警,这些活动是使用同一活动中的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);
    }

}
}

0 个答案:

没有答案