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

私が見る問題は、繰り返しTimeInMillisのタイプとしてintを使用していることです。タイムスタンプには常にlong型を使用する必要があります。int の容量が十分でないため、オーバーフローしてピリオドが負の数になる可能性があります。

また

System.currentTimeMillis()* repeatingTimeInMillis

間違いなく間違っているようです。乗算するのではなく、現在の時間に時間オフセットを追加する必要があります。

于 2013-05-14T10:43:24.197 に答える