我有一个服务“GroupsTaskAlarmChecker”,AlarmManager 在 Groups.class 活动的 onCreate 中每 20 秒调用一次:
int seconds = 20;
Intent myIntent = new Intent(Groups.this, GroupsTaskAlarmChecker.class);
pendingIntent = PendingIntent.getService(Groups.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);
这完美地工作。但是我需要在设备启动时这样做。然后我知道我必须像这样制作 AndroidManifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".ReceiverBoot">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
<category android:name="android.intent.category.HOME">
</category></action></intent-filter>
</receiver>
然后像这样 mi broadcastReceiver :
public class ReceiverBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int seconds = 20;
Intent myIntent = new Intent(context, GroupsTaskAlarmChecker.class);
pendingIntent = PendingIntent.getService(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), seconds * 1000, pendingIntent);
}
}
但是在这个 onReceive 里面我不知道我怎么能像以前一样做(意图和 alarmManager 每 20 秒启动一次服务)。此行中的错误:
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
有可能我不能在 BroadcastReceiver 中创建一个 AlarmManager 吗?
谢谢大家,我是一名 Android 初学者,我需要你们的帮助。对不起我的英语不好 ;)