简体   繁体   中英

AlarmManager fires twice in Android Version 4.4.2 KitKat

I have an alarmManager that fires one time in all Android Versions, but only in Version 4.4.2 it fires twice. I read that there were changes in this version that affected AlarmManager, but I don't know how to workaround it, and if this is the case here... Any suggestions?

This is the code:

public void setOneTimeTimer(Context context, int id)
{
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");

    if ((wakelock==null) | ((wakelock != null) && (wakelock.isHeld() == false))){
        wl.acquire();
        wakelock = wl;
        //Release wakeLock is in the Alarm Class
    }

    AlarmManager am = (AlarmManager)NoteActivity.this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(NoteActivity.this, Alarm.class);
    intent.putExtra("name", name);
    intent.putExtra("phone", phone);
    intent.putExtra("timeSet", timeSet);
    PendingIntent pi = PendingIntent.getBroadcast(NoteActivity.this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
        setAlarm(am, interval, pi);
    }
    else
    {
        setAlarmToKitkat(am, interval, pi);
    }
}

private void setAlarm(AlarmManager am, long interval, PendingIntent pi){
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, pi);
}
@TargetApi(19)
private void setAlarmToKitkat(AlarmManager am, long interval, PendingIntent pi){
    am.setWindow(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + interval, 20000, pi);
} 

在此处输入图片说明

So I'll write here my solution in case it will help someone in the future: The problem was that I set the alarm at a "onTimeSet" method of TimePickerDialog and for some reason only on KitKat version it activated the alarm twice. When I added an empty(!) method of a positive button, it worked out and activated the alarm method only once... That was the method I added:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
    timePicker.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.title_ok), new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            if (which == DialogInterface.BUTTON_POSITIVE) {

                                            }
                                        }
                                    }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM