简体   繁体   中英

AlarmManager does not fire on some devices?

I'm creating an application which uses PendingIntent with AlarmManager for notifications. So like every 12 hours, the app should connect to the web server and retrive some info, if any. When I've tested this code with 1minute delay, it was working great. But now before publishing my app, I wanted to test this code and see what my users will get, but I'm facing a problem now.

I've tested on two devices. One went to sleep (idle for 7hours), and this device didn't receive any notifications. Second device did get notifications, but It was forced not to sleep ( I used app for this ). Well I'm just assuming that this is it, because there is no other explanation. Because I used AlarmManager. Here is my brief code.

 public void setAlarm(boolean isCanceled) {

        Intent intent = new Intent(NOTIFICATION_TIME);



        if(!isCanceled) {


            pendingIntent = PendingIntent.getBroadcast(activityContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+TWELVEHOURS, TWELVEHOURS, pendingIntent);

        } else {

            pendingIntent = PendingIntent.getBroadcast(activityContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        }
    }

"isCanceled", cancels the alarm only if you make changes in settings. So this is not it.

Is this implemented right, and it should launch my broadcast receiver, or.. ?

Use following code,

    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb");
    wl.acquire();

This will wake your CPU and then perform the code that you want to execute when Alarm fires.

You need to device following permission in your AndroidManifest.xml file

<uses-permission android:name="android.permission.WAKE_LOCK" />

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