我使用以下方法创建了一个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);
}
});
为什么会这样?
答案 0 :(得分:1)
我看到的问题是你使用 int 作为repeatingTimeInMillis的类型。您应始终使用 long 类型作为时间戳。 int的容量不够,所以你可能有溢出将你的句号转为负数。
另外
System.currentTimeMillis()* repeatingTimeInMillis
肯定是不正确的。您将时间偏移添加到当前时间,而不是将其倍增。