Search code examples
androidandroid-intentbroadcastreceiver

BroadcastReceiver repeats without change


I call a BroadcastReceiver from an Activity

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);

Its onReceivemethod is this:

        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);

Basially, every time the Receiver is called, it should show a Toast It's Running plus an incremented value(1,2,3 etc). However, it always shows It's Running 0. What am I doing wrong?


Solution

  • Because lol isn't getting incremented!

    Your concept is totally wrong ~

    int lol and String lol are different objects. You have to pass the same object in both areas like below.

    Class 1 : (Activity)

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

    Class 2 : (Receiver)

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

    Otherwise

    Increment lol in Class 1, then send the value to Class 2. Just implement toast in Class 2.

    Like :

    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
    }
    

    Besides that, why you're trying to launch 2nd class from the code exists in itself? Isn't a bad and complex idea, even not working as your question suggest.