gpt4 book ai didi

java - Android 中广播接收器的 AlarmManager

转载 作者:太空宇宙 更新时间:2023-11-04 13:27:56 25 4
gpt4 key购买 nike

我一直在尝试使用 AlarmManager 重复某个操作,但是,它一次工作正常,然后在 20 秒后不再重复。

public class CheckingService extends Service {
private static final String APP_TAG = "com.test";

@Override
public IBinder onBind(final Intent intent) {
return null;
}

@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
Log.d(APP_TAG, "event received in service: " + new Date().toString());
Toast.makeText(CheckingService.this, "TEST", Toast.LENGTH_SHORT).show();
return Service.START_NOT_STICKY;
}
}

用于安排警报的广播接收器:

public class SchedulerReciever extends BroadcastReceiver {
public SchedulerReciever() {
}

private static final String APP_TAG = "com.test";

private static final int EXEC_INTERVAL = 20 * 10;

@Override
public void onReceive(final Context ctx, final Intent intent) {
Log.d(APP_TAG, "onReceive() called");
AlarmManager alarmManager = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(ctx, MyBraoadCastReciever.class); // explicit
// intent
PendingIntent intentExecuted = PendingIntent.getBroadcast(ctx, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar now = Calendar.getInstance();
now.add(Calendar.SECOND, 2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
now.getTimeInMillis(), EXEC_INTERVAL, intentExecuted);
}
}

我加载服务的广播接收器:

public class MyBraoadCastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {


Intent eventService = new Intent(context, CheckingService.class);
context.startService(eventService);

}
}

最后我的 AndroidManifest.xml 正在使用启动

<receiver android:name=".SchedulerReciever" android:process=":my_process">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>

<service android:name=".CheckingService" android:process=":my_process" >
</service>


<receiver
android:name=".MyBraoadCastReciever" android:process=":my_process"
android:enabled="true"
android:exported="false" >
</receiver>

最佳答案

您的 EXEC_INTERVAL 设置为 200 毫秒,而不是 20 * 1000(20 秒)。

此外,如果您使用 setRepeating,最好使用相对时间 AlarmManager.ELAPSED_REALTIME_WAKEUP(自手机启动以来的时间),并且无需创建日历,您只需调用 SystemClock.elapsedRealtime() 或使用可选的 2 秒偏移量 SystemClock.elapsedRealtime() + 2000

所以你的重复集应该是这样的:

alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 2000, EXEC_INTERVAL, intentExecuted);

关于java - Android 中广播接收器的 AlarmManager,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467509/

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