我尝试在20秒后广播,并使用扩展的接收器ExtendedReceiver接收广播。

这是我的函数,该函数会创建警报并将PendingIntent设置为在20秒后关闭:

public void alert() {
    GregorianCalendar cal = new GregorianCalendar();
    cal.add(Calendar.SECOND, 20);

    Intent i = new Intent(this, ExtendedReceiver.class);
    int _uid = (int) System.currentTimeMillis();
    PendingIntent pi = PendingIntent.getBroadcast(this, _uid, i, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);

    Log.i("Title", "Alarm has been set");
}

这是ExtendedReceiver类:
public class ExtendedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Title", "Broadcast received");
    }
}

我收到第一条日志消息:Alarm has been set,但没有收到第二条日志消息。我不确定问题出在哪里(Android的第一天)

最佳答案

如果可以的话,这就是我一直在做的事情。

改变你的

PendingIntent pi = PendingIntent.getBroadcast(this, _uid, i, PendingIntent.FLAG_ONE_SHOT);


 PendingIntent pi = PendingIntent.getBroadcast(this, _uid, new Intent(EXTENDED_RECEIVER_ACTION), PendingIntent.FLAG_ONE_SHOT);

重要提示:像这样注册ExtendedReceiver:
...
registerReceiver(new ExtendedReceiver() , new IntentFilter(EXTENDED_RECEIVER_ACTION));

PS:EXTENDED_RECEIVER_ACTION是一个字符串,不要忘记注销接收者。

进一步的文档here

希望能帮助到你 :)

07-26 09:29