简体   繁体   中英

AlarmManager repeats call even if its not time

I'm using alarm manager to call for api. it is called in a activity onCreate. I want it to call an alarm at start of the app then alarms every three hours.

Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY,1);
    AlarmManager alarmManager1 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent myIntent1 = new Intent(LobbyActivity.this,WeatherBroadCastReceiverCurrent.class);
    PendingIntent pendingIntent1 = PendingIntent.getBroadcast(this,0,myIntent1,0);

    alarmManager1.setInexactRepeating(AlarmManager.RTC,calendar.getTimeInMillis(),AlarmManager.INTERVAL_HOUR+
            AlarmManager.INTERVAL_HOUR+AlarmManager.INTERVAL_HOUR/*(1000*60*60*3)*/,pendingIntent1);

That activity is then finished and proceeds to another activity when a button is clicked. My problem is-if the activity is recreated it calls an alarm even if it is not the time. Can I set an alarm on a non activity class so it will not be recalled when the activity is recreated?? if so how? Tia

try to run by removing calendar.set(Calendar.HOUR_OF_DAY,1); and run, it will call alarm at start of app

To simply get over this, you need to create a flag and make it true so that the activity can check if the Alarm has been set before, it is has, then it will move forward without setting it.

Use of SharedPreferences is ideal for this. This is one of my snippets, edit it according to your need.

SharedPreferences prefs;
SharedPreferences.Editor ed;
prefs = PreferenceManager.getDefaultSharedPreferences(this);
ed = prefs.edit();
boolean isOpeningForTheFirstTime = prefs.getBoolean("firstTime", true);

if(!isOpeningForTheFirstTime) {
    Intent i = new Intent(this, StartScreen.class);
    startActivity(i);
    finish();
}

And the AlarmManager can be simplified by removing a few things.

public void setAlarm(){

    //To get the current time
    long alertTime = new GregorianCalendar().getTimeInMillis();

    //Interval of a minute
    int timeInterval = 60000;

    //Intent which you want to start
    Intent alertIntent = new Intent(this, ClassName.class);

    //Declaring the alarmManager
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Setting the alarmmanager up.
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alertTime, timeInterval, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
}

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