简体   繁体   English

AlarmManager在某些设备上无法启动?

[英]AlarmManager does not fire on some devices?

I'm creating an application which uses PendingIntent with AlarmManager for notifications. 我正在创建一个使用PendingIntent和AlarmManager进行通知的应用程序。 So like every 12 hours, the app should connect to the web server and retrive some info, if any. 因此,就像每12个小时一样,该应用应连接到网络服务器并检索一些信息(如果有)。 When I've tested this code with 1minute delay, it was working great. 当我以1分钟的延迟测试此代码时,它的运行效果很好。 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. 一个人进入睡眠状态(闲置7个小时),并且该设备未收到任何通知。 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. 因为我使用了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. “ isCanceled”,仅当您更改设置时才取消警报。 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. 这将唤醒您的CPU,然后执行警报触发时要执行的代码。

You need to device following permission in your AndroidManifest.xml file 您需要在AndroidManifest.xml文件中设备遵循以下权限

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM