0

我使用以下方法创建了一个 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);
        }
    });

为什么会这样?

4

1 回答 1

1

我看到的问题是您使用int作为 repeatingTimeInMillis 的类型。您应该始终使用类型的时间戳。int 的容量不够,所以你可能有溢出将你的周期变成负数。

System.currentTimeMillis()* repeatingTimeInMillis

绝对看起来不正确。您应该将时间偏移量添加到当前时间,而不是相乘。

于 2013-05-14T10:43:24.197 回答