WakefulBroadcastReceiver没有从AlarmManager接收PendingIntent

时间:2015-03-09 17:18:37

标签: android broadcastreceiver alarmmanager android-pendingintent android-alarms

我在一个必须以指定间隔重复任务的应用上挣扎。如果需要,我希望它能唤醒设备。我不明白为什么,但是 WakefulBroadcastReceiver 从不执行应该通过AlarmManager触发的 onReceive 方法。普通的BroadcastReceiver问题仍然存在。我使用的是Lollipop 5.0.1 Nexus5,时间间隔为5-20秒。

以下是代码:

class mypackage.MainActivity

[...]
private void startRepeatingAlarm(){
    this.wbr = new SimpleWakefulBroadcastReceiver();
    this.registerReceiver(wbr, new IntentFilter("mypackage.FOO_ACTION"));
    Intent i = new Intent("mypackage.FOO_ACTION");
    i.setClass(this, SimpleWakefulBroadcastReceiver.class);

    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 1234, i, PendingIntent.FLAG_CANCEL_CURRENT);      
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);      
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), timeInterval, pendingIntent);
    Toast.makeText(this, "Alarm set", Toast.LENGTH_SHORT).show();
}

class mypackage.SimpleWakefulBroadcastReceiver

public class SimpleWakefulBroadcastReceiver extends WakefulBroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    // This method gets NEVER called
    Intent service = new Intent(context, SimpleWakefulService.class);
    startWakefulService(context, service);
}}

2 个答案:

答案 0 :(得分:2)

我要把我的脖子伸到这里猜猜你没有在你的清单中宣布广播接收器:

<receiver android:name=".SimpleWakefulBroadcastReceiver"/>

答案 1 :(得分:-1)

private void startRepeatingAlarm(){    
 Intent intent = new Intent(MainActivity.this, SimpleWakefulBroadcastReceiver.class);
                intent.setAction(Intent.ACTION_MAIN);
                pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
                        0, intent, 0);
              //repeat per 1 min
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1 * 60 * 1000, pendingIntent);

}