gpt4 book ai didi

android - 不从 AlarmManager 调用 BroadcastReceiver

转载 作者:行者123 更新时间:2023-11-29 02:36:30 27 4
gpt4 key购买 nike

我不想看到 Oreo 的 AlarmManager setExactAndAllowWhileIdle 是如何工作的,并为此编写了非常简单的服务,但它不起作用,我真的不明白原因。到目前为止我看到的所有原因都与我的代码无关。请指导我哪里出错了。

主 Activity

   private void startService() {
Log.d("testt", "MainActivity - startService");
Intent intent = new Intent(this, LocationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,intent,PendingIntent.FLAG_UPDATE_CURRENT );
AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() + 60 * 1000, pendingIntent);
}

广播接收者

public class LocationReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("testt", "LocationReceiver - onReceive");
Intent i = new Intent(context, LocationService.class);
context.startService(intent);
}
}

服务

public class LocationService extends IntentService {
public LocationService() {
super("any_name");
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.d("testt", "LocationService - onHandleIntent");
}
}

终于显现

    <service android:name=".LocationService" android:exported="false"/>
<receiver android:name=".LocationReceiver"/>
</application>

最佳答案

关于您 Activity 中的这行代码:

alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis() +  60 * 1000, pendingIntent);

您想要使用 SystemClock.elapsedRealtime() 而不是 System.currentTimeMillis();您的代码应如下所示:

alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +  60 * 1000, pendingIntent);

您需要使用自设备启动以来的毫秒数开始间隔时间计算,而不是自 1/1/1970 以来的毫秒数。

关于android - 不从 AlarmManager 调用 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695611/

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