AlarmManager don't run as expectly

流过昼夜 提交于 2019-12-12 03:03:04

问题


As you suggested me to use AlarmManager instead of Timer, I thought, the program will run.
But unfortunately, it does not. Or, better, not always...

This is my code:

long millis = 0;

this.alarmMgr = (AlarmManager)this.main.getSystemService(Context.ALARM_SERVICE);

this.checkPendingIntent = PendingIntent.getBroadcast(this.main, 0,
              new Intent(this.main, AlarmReceiver.class), 0);

if(frequency.compareTo("1HOUR") == 0)
  millis = 3600 * 1000;
if(frequency.compareTo("12HOUR") == 0)
  millis = 12 * 3600 * 1000;
if(frequency.compareTo("1DAY") == 0)
  millis = 24 * 3600 * 1000;
if(frequency.compareTo("1WEEK") == 0)
  millis = 7 * 24 * 3600 * 1000;

this.alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis(), millis, this.checkPendingIntent);

I'm expecting that the pending intent (AlarmReceiver) will be called every X milliseconds, but it does not.
I can see in the logs of my phone, that it will not be called, and in the log of my server (the receiver sends an HTTP-Request), that no requests are received.

VERY strange is, that sometime it runs, but I can't reproduce the situation.

Can someone say me what am I doing wrong?

Thanks a lot
Luca Bertoncello


回答1:


This is a simple example of how to use the Alarm

Calendar now = Calendar.getInstance();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, yourHour);
calendar.set(Calendar.MINUTE, yourMin);
calendar.set(Calendar.SECOND, youSec);

if (calendar.before(now)) { //if time passed
    calendar.add(Calendar.DATE,1);
}
Intent intent = new Intent(Context.this, DestinationActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity
               (Settings.this,123456, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                                        AlarmManager.INTERVAL_DAY,pendingIntent);

Use setRepeating if you want your alarm to be Repeated daily.
If you don`t want use setAlarm(..,..,..,..) instead




回答2:


check out this-

Intent intentalarm = new Intent("com.mubble.powercutsensorapp.MYTIMER");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentalarm, 0);
    AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
    long now = System.currentTimeMillis();
    long interval = 24*60 * 60 * 1000; // 24 hour
    manager.setRepeating(AlarmManager.RTC_WAKEUP, now + interval, interval,
        pendingIntent); 


来源:https://stackoverflow.com/questions/16249057/alarmmanager-dont-run-as-expectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!