Issues alarm manager in every 1 min Android?

点点圈 提交于 2019-12-01 23:37:28

问题


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 Receiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {

            Toast.makeText(getBaseContext(), "Alarm", Toast.LENGTH_LONG).show();
            NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); 
            AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
            Intent i=new Intent(context, ConnectionReceiver.class);
            PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
            mgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1*60*1000, pi);
        }
}

回答1:


Juts register broadcast receiver for:

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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/8999103/issues-alarm-manager-in-every-1-min-android

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