Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send data to the alarm manager broadcast receiver

I am missing something here and I hope someone can help me out. I am setting up an alarm using the following:

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    Intent broadcast_intent = new Intent(this, AlarmBroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);

    broadcast_intent.putExtra("test", "ValueReceived"); //data to pass
    Date date = someVariable.getDateTime();


    long triggerAtTime = date.getTime();

    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtTime, pendingIntent);

and the broadcast receiver using the following:

public class AlarmBroadcastReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {

        Toast.makeText(context, "Alarm has been received "+intent.getStringExtra("test"), Toast.LENGTH_LONG).show();

    }

}

However intent s apperently "empty". I am seeing null value for the getStringExtra. So the data is not being passed to the broadcast receiver. What am I doing wrong? How can I pass data.

Thank you so much

like image 789
Snake Avatar asked Sep 18 '12 04:09

Snake


People also ask

How to use alarm manager?

This example demonstrates how do I use AlarmManager in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How AlarmManager works in android?

The Alarm Manager holds a CPU wake lock as long as the alarm receiver's onReceive() method is executing. This guarantees that the phone will not sleep until you have finished handling the broadcast. Once onReceive() returns, the Alarm Manager releases this wake lock.

How to set alarm using AlarmManager in android?

The activity class starts the alarm service when user clicks on the button. Let's create BroadcastReceiver class that starts alarm. You need to provide a receiver entry in AndroidManifest. xml file.

What is an exact alarm?

The new exact alarm permission ( SCHEDULE_EXACT_ALARM ) was created to save system resources. Alarms that must be executed in an exact time may be triggered when the phone is on power-saving mode or Doze, making the app consumes more battery than it should.


1 Answers

You need to add the extras to the Intent before you pass it to the PendingIntent:

Intent broadcast_intent = new Intent(this, AlarmBroadcastReceiver.class);
broadcast_intent.putExtra("test", "ValueReceived"); //data to pass

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);
like image 102
Theus Avatar answered Sep 18 '22 13:09

Theus