我使用以下方法创建了一个 BroadcastReceiver :
public void SetAlarm(Context context, int repeatingHours)
{
int repeatingTimeInMillis = 1000 * 60 * 60 * repeatingHours; // Millisec * Second * Minute * Hours where x is time between each alarm.
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AutoUpdateReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()* repeatingTimeInMillis, repeatingTimeInMillis, pi);
Toast.makeText(context, "Alarm set to repeat every " + repeatingHours + " hours", Toast.LENGTH_SHORT).show();
}
但是,一旦我调用 SetAlarm,似乎 onReceive 就会不断关闭。
如果这与任何方式相关,这就是我调用 SetAlarm 的地方:
receiver = new AutoUpdateReceiver();
howOftenRadioGroup.setOnCheckedChangeListener(new android.widget.RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
SharedPreferences prefEditor = getSherlockActivity().getSharedPreferences("com.kamstrup.ecamp", Context.MODE_PRIVATE);
int repeatingHours = 0;
switch(checkedId)
{
case R.id.auto_update_radio_hour_1:
repeatingHours = 1;
prefEditor.edit().putInt(SETTINGS_KEY, repeatingHours).commit();
break;
case R.id.auto_update_radio_hour_3:
repeatingHours = 3;
prefEditor.edit().putInt(SETTINGS_KEY, 3).commit();
break;
case R.id.auto_update_radio_hour_6:
repeatingHours = 6;
prefEditor.edit().putInt(SETTINGS_KEY, 6).commit();
break;
case R.id.auto_update_radio_hour_12:
repeatingHours = 12;
prefEditor.edit().putInt(SETTINGS_KEY, 12).commit();
break;
default:
break;
}
receiver.SetAlarm(getSherlockActivity(), repeatingHours);
}
});
为什么会这样?