挂起意图的广播接收器不起作用

时间:2015-04-18 12:56:07

标签: android broadcastreceiver

尝试发送广播并在特定时间接收广播。 我注册广播的A类RegisterBroadcast方法:

cal = Calendar.getInstance();
int lap = 1000 * 60 * 10;
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR, 5);
cal.set(Calendar.MINUTE, 01);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), lap, pi);
Intent i = new Intent(getApplicationContext(), MyAlarm.class);
pi = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);

接收器:

@Override
public void onReceive(Context cont, Intent i) {
    Toast.makeText(cont, "I am broadcasting", Toast.LENGTH_LONG).show();
}

清单:

<receiver android:name="com.anarkali.MyAlarm">

但是这段代码无法正常播放。有时它确实有时不是为什么?我很困惑。

1 个答案:

答案 0 :(得分:2)

您似乎在初始化之前使用PendingIntent pi,在这种情况下,它会使用当时分配给pi的任何值,这可能是旧PendingIntent 1}}或可能null

am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),lap,pi);
Intent i = new Intent(getApplicationContext(),MyAlarm.class);
pi=PendingIntent.getBroadcast(getApplicationContext(), 0,i,0);

应该是:

Intent i = new Intent(getApplicationContext(),MyAlarm.class);
pi=PendingIntent.getBroadcast(getApplicationContext(), 0,i,0);
am.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(),lap,pi);