BroadcastReceiver无需更改即可重复播放

时间:2018-06-11 15:52:58

标签: android android-intent broadcastreceiver

我从一个Activity

调用一个BroadcastReceiver
Intent alarmIntent = new Intent(MainActivity.this, AlarmRec.class);
            alarmIntent.putExtra("lol",0);
            pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pendingIntent);

它的onReceive方法是这样的:

        int lol=intent.getExtras().getInt("lol");
    Toast.makeText(context, "I'm running "+lol, Toast.LENGTH_SHORT).show();
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    lol++;
    Intent alarmIntent = new Intent(context, AlarmRec.class);
    alarmIntent.putExtra("lol",lol);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    manager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pendingIntent);

基本上,每次调用Receiver时,它都应显示Toast It's Running加上递增值(1,2,3等)。然而,它始终显示它正在运行0.我做错了什么?

1 个答案:

答案 0 :(得分:1)

因为lol没有增加!

您的概念是完全错误的〜

int lolString lol是不同的对象。您必须在如下两个区域中传递相同的对象。

第1类:(活动)

....
AlarmManager manager =...
....
manager.setRepeating(.....); //use to repeat + don't need to pass lol

第2类:(接收方)

.... 
public static int LOL = 0;
....
onReceive(....){
LOL++;
Toast.makeText(....,(String)LOL,....).show();
}

否则

在类1中递增lol,然后将值发送到Class 2。只需在第2类中实现吐司。

赞:

int lol =0
for(;;) {   //a forever loop which runs until your device die
sendToClass2(lol++);
}

private void sendToClass2(int foe){
....
alarmIntent.putExtra("lol",foe);
....
manager.setExact(...); // If you really love to use seExact use this
}

此外,为什么要尝试从代码本身启动第二类呢?这不是一个糟糕而复杂的想法,即使按照您的问题建议也不起作用。