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
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.
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With