android – 当BOOT_COMPLETED时,BroadcastReceiver里面的AlarmManager

前端之家收集整理的这篇文章主要介绍了android – 当BOOT_COMPLETED时,BroadcastReceiver里面的AlarmManager前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个服务“GroupsTaskAlarmChecker”,它由GroupsManager在onCreate的Groups.class活动中每隔20秒调用一次:
int seconds = 20;

           Intent myIntent = new Intent(Groups.this,GroupsTaskAlarmChecker.class);
           pendingIntent = PendingIntent.getService(Groups.this,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);

        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.SECOND,10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,pendingIntent);

    }
}

但是在这个onReceive里面我不知道我怎么能像以前那样做(使用intent和alarmManager每20秒启动一次服务).
这行错误

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

有可能我无法在BroadcastReceiver中创建一个AlarmManager吗?

我感谢你们所有人,我是一个Android问候者,我需要你的帮助.对不起我的英语不好

猜你在找的Android相关文章