简体   繁体   English

PendingIntent和AlarmManager

[英]PendingIntent and AlarmManager

I'm trying to broadcast after 20 seconds and receive the broadcast with an extended receiver ExtendedReceiver . 我试图在20秒后播出并使用扩展接收器ExtendedReceiver接收广播。

Here is my function that creates an alarm and sets the PendingIntent to go off after 20 seconds: 这是我的函数,它创建一个警报并将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");
}

Here is the ExtendedReceiver class: 这是ExtendedReceiver类:

public class ExtendedReceiver extends BroadcastReceiver {

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

I get my first log message: Alarm has been set but I don't get my second log message. 我收到第一条日志消息: Alarm has been set但我没有收到第二条日志消息。 I'm unsure where the problem lies (first day on Android) 我不确定问题出在哪里(Android上的第一天)

If i may this is what i always do. 如果我可能这是我一直以来做的事情。

change your 改变你的

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

to

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

and important: Register your ExtendedReceiver like this: 并且重要:注册您的ExtendedReceiver如下所示:

...
registerReceiver(new ExtendedReceiver() , new IntentFilter(EXTENDED_RECEIVER_ACTION));

PS: EXTENDED_RECEIVER_ACTION is a String and dont forget to unregister your receiver. PS:EXTENDED_RECEIVER_ACTION是一个字符串,别忘了取消注册您的接收器。

further docs here 进一步的文档在这里

hope it helps :) 希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM