gpt4 book ai didi

从未决 Intent 接收广播的Android问题

转载 作者:太空狗 更新时间:2023-10-29 14:12:45 25 4
gpt4 key购买 nike

我正在使用警报管理器在特定时间触发广播。但是经过多次测试,我发现有时广播会延迟接收。有时 5 秒、10 秒、15 秒甚至更多。特别是当设备被锁定时。我做过各种实验。我的问题最少的代码在这里。

即使使用了唤醒锁,我也不知道自己缺少什么。

Firing Intent

Intent intent = new Intent(this.getApplicationContext(), BroadCastReceiver.class);  
//..... some extras
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), code, intent, 0);
manager.setRepeating(AlarmManager.RTC_WAKEUP, time, 1000 * 120 , pi);

Receiving broadcast

public void onReceive(Context context, Intent intent)
{
WakeLocker.acquire(context);
.......
Intent alarm = new Intent(context, xyz.class);
alarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(alarm);
}

并在 xyz Activity 的 destroy() 中释放唤醒锁。

Custom WakeLocker class public abstract class WakeLocker {

private static PowerManager.WakeLock wakeLock;

public static void acquire(Context ctx) {
if (wakeLock != null) wakeLock.release();

PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "haris");
wakeLock.acquire();
}

public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}

最佳答案

根据official documentation :

AlarmManager.setRepeating(...)
as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.

这意味着你必须在收到它时重新设置你的PendingIntent。
像这样:

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
switch (intent.getAction()) {
case AlarmHelper.ACTION_MY_ALARM:
doWhatYouNeed();
long nextTime = getNextAlarmTime();
AlarmHelper.resetAlarm(nextTime);
break;
...
}
}
}

要获得下一个闹钟时间,您可以使用 System.currentTimeMillis() + interval 或将其传递给 intents extras,第二种方式更准确。而且,我敢肯定,您不需要 BroadcastReceiver 中的 WakeLock。

public class AlarmHelper {
public static void resetAlarm(long time) {
Intent intent = createIntent();
PendingIntent pendingIntent = createPendingIntent(intent);
setAlarmManager(time, pendingIntent);
}

public static void setAlarmManager(long time, PendingIntent pendingIntent) {
AlarmManager alarmManager = (AlarmManager) MyApp.getAppContext().getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
}
}

关于从未决 Intent 接收广播的Android问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25540374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com