2 myc 100 myc_100 于 2013.05.17 09:45 提问

AlarmManager 有时候不能调用 BroadcastReceiver

在程序中我获得一个 BroadcastReceiver,被一个 AlarmManager 调用。BroadcastReceiver调用 CommonsWare 的 WakefulIntentservice.
我在电话上测试,看起来有时候 BroadcastReceiver 根本不能被调用。我不知道什么原因。 我在 manifest中申明了 BroadcastReceiver 和 WakefulIntentservice。
我查资料说设置一个BroadcastReceiver会返回 onBootCompleted。
AlarmActivity 代码:

Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 2);

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), savedIntervalAutomaticMilisInt, pendingIntent);

Toast.makeText(this, "Saved", Toast.LENGTH_LONG).show();

finish();

AlarmReceiver:

package com.something.app;

import com.commonsware.cwac.wakeful.WakefulIntentService;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, AlarmService.class);
        WakefulIntentService.sendWakefulWork(context, i);
    }
}

AlarmService:

package com.something.app;

import android.app.PendingIntent;
import android.content.Intent;
import com.commonsware.cwac.wakeful.WakefulIntentService;

public class AlarmService extends WakefulIntentService {

    public AlarmService() {
        super("AlarmService");
    }

    @Override
    protected void doWakefulWork(Intent arg0) {
        //A looooooooot of stuff
    }

为什么 BroadcastReceiver 有时候不能被调用?

1个回答

xiaoyan_12
xiaoyan_12   2013.05.17 15:41

如果重启设备的话,它有时会清除报警。所以你应该在一个 BroadcastReceiver 重置他们再接收 onBootCompleted。

Csdn user default icon
上传中...
上传图片
插入图片