![](/img/trans.png)
[英]Android – Trouble with AlarmManager and BroadcastReceiver
[英]AlarmManager for BroadcastReceiver in Android
我一直在嘗試使用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;
}
}
BroadcastReceiver計划警報:
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
設置為200ms,而不是20 * 1000(20s)。
另外,如果使用setRepeating,最好使用相對時間AlarmManager.ELAPSED_REALTIME_WAKEUP
,這是自電話啟動以來的時間,而不是創建日歷,您可以僅調用SystemClock.elapsedRealtime()
或使用2s的可選偏移量SystemClock.elapsedRealtime() + 2000
。
因此,您的重復設置應如下所示:
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 2000, EXEC_INTERVAL, intentExecuted);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.