1
我一直在试图用AlarmManager重复一个动作,但是它一次正常工作,然后在20秒后不再重复。AlarmManager为广播回收机器人android
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;
}
}
BroadcastReciever安排的Alaram:
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>
谢谢,它的工作 –