Issues alarm manager in every 1 min Android?

前端 未结 3 1611
栀梦
栀梦 2021-01-20 17:33

I want to make a service which fire alarm manager in every 1 min interval..But my Alarm run once(first time only). I follow Lalit Answer

private class Rec         


        
相关标签:
3条回答
  • 2021-01-20 17:39

    Try this code in Your broadcast receiver's onReceive method

    AlarmManager mgr=(AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
    mgr.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                                  60000+System.currentTimeMillis(),
                                      getPendingIntent(ctxt));
    

    and you can get pending intent

    private static PendingIntent getPendingIntent(Context ctxt) {
        Intent i=new Intent(ctxt, AReceiver.class);
        return(PendingIntent.getBroadcast(ctxt, 0, i, 0));
    }
    

    where AReceiver class is for start service like Notification it is working fine in my app so i hope it helps you

    0 讨论(0)
  • 2021-01-20 17:48

    I know this question already has an answer, but for others who have had the same issue but need to use AlarmManager. The reason why it only runs once is because the new PendingIntent you create does not get recreated, but rather is reusing the one before it. So in other words, the reason why your alarm only ran once was because it kept reusing it. Using the flags to refresh the intent extras if there are any should be doing the trick, but that also does not work.

    A trick to use to make sure it does not reuse the PendingIntent and ultimately the Intent you provide is to use setAction() and give it some unique "Action". I did it like this:

    intent.setAction("com.yourname."+System.currentTimeMillis());
    

    As you see this makes sure its unique. Though, the above accepted answer it the best approach, if someone does not want that, they need to understand why and how to remedy that issue. Hope it helps anyone else.

    0 讨论(0)
  • 2021-01-20 17:57

    Juts register broadcast receiver for:

    http://developer.android.com/reference/android/content/Intent.html#ACTION_TIME_TICK

    0 讨论(0)
提交回复
热议问题