receiving ID of Pending Intent from Broadcast Receiver - android

I need to access the ID of the Pending Intent from the Broadcast Receiver class.
Here is the code of my Main Activity from which I set the Alarm using PendingIntent.
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(AddAlarm.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, pen, alarmintent, PendingIntent.FLAG_ONE_SHOT); //where pen is the ID
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
And here is the code of my Broadcast Receiver:
public class AlarmReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
int vibrator = intent.getIntExtra("vibrator", 1);
//PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
//intent to call the activity which shows on ringing
Intent myIntent = new Intent(context, Time_Date.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
//display that alarm is ringing
Toast.makeText(context, "Alarm Ringing...!!!", Toast.LENGTH_LONG).show();
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
Can I use Intent.putExtra() to receive the same or any other easy way to get the unique ID to the Broadcast Receiver? Any help will be appreciated.

I don't think the second argument to PendingIntent.getBroadcast() is meant to be used by the component that eventually receives the intent (at least I have found no way to access it). If you want to pass some data along that is specific to your app, just use an extra.

Related

How to pass data through PendingIntent to Broadcast receiver

I'm developing alert app which shows notification and custom message in separate activity when alarm is set off.I'm facing problem in sending identifier to broadcast receiver which is useful in fetching data from database.
I have gone through various blogs, stackoverflow posts but couldn't find the working solution.Please do help me.
My function for scheduling alarm.
void setAlarm(int tag, long time) {
Intent myIntent = new Intent(context, AlarmReceiver.class);
myIntent.putExtra("TEST", "dummy");
myIntent.putExtra("ID",tag);
pendingIntent = PendingIntent.getBroadcast(context, tag, myIntent, Intent.FILL_IN_DATA);
alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}
My Broadcast receiver
#Override
public void onReceive(Context context, Intent intent) {
logHelper.printLog("Alarm Service "+intent.getIntExtra("ID",0)+ intent.getStringExtra("TEST"));
ComponentName comp = new ComponentName(context.getPackageName(),
AlarmService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
Kindly let me know if any further information needed.

Pending intent with different intent but same ID

I have two pending Intent to use with Alarm Manager one is:
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,0,i,PendingIntent.FLAG_CANCEL_CURRENT);
and the other is:
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,0, i,PendingIntent.FLAG_CANCEL_CURRENT);
I use these two in different methods in my application
my question is:
Are these pendingIntents differnt from each other?? because the intents are different but the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
So the easy way is test it directly by yourself.
I have tested it on my computer and here is what i got:
Are these pendingIntents different from each other?? because the intents are different but the Ids are same
-Yes they are different each other although the Ids are same
If I set alarm manager for each of these pending intent do both of them trigger or one replace another?
-Both of them will be triggered
Here are my code for test, you can copy and try it by yourself
Copy this method to your activity, and call it
private void setAlarmManager() {
Log.v("AlarmManager", "Configuring AlarmManager...");
Intent startIntent1 = new Intent(context, AlarmReceiverFirst.class);
PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context, 0, startIntent1, PendingIntent.FLAG_CANCEL_CURRENT);
Intent startIntent2 = new Intent(context, AlarmReceiverSecond.class);
PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 0, startIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 20);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Log.v("AlarmManager", "Starting AlarmManager for >= KITKAT version");
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
} else {
Log.v("AlarmManager", "Starting AlarmManager for < KITKAT version");
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent1);
alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent2);
}
Log.v("AlarmManager", "AlarmManager has been started");
}
Create your first receiver class
public class AlarmReceiverFirst extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "first alarm receiver is called");
}
}
Create your second receiver class
public class AlarmReceiverSecond extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.v(this.getClass().getSimpleName(), "second alarm receiver is called");
}
}
Register those receivers to your manifest
<receiver android:name=".AlarmReceiverFirst" />
<receiver android:name=".AlarmReceiverSecond" />
Not to be confused, what you called Id here is called request code. It is used for cancelling the pending intent.
Intents are just the action PendingIntent is bound to execute once it triggers. But this triggering criteria are entirely depending on PendingIntent itself and RequestCode is playing here a pretty good role to uniquely identify, manage and trigger PendingIntent.
Therefore, no matter what the Intent is, if the requestCode is repeated then the latter PendingIntent will trigger. If you need to trigger multiple PendingIntents, the requestCode must be different from each other.
You can have same name of intents but with different ids like following,
Intent i = new Intent(context, TriggerAlarm.class);
PendingIntent pi =PendingIntent.getBroadcast(context,System.currentTimeMillis(),i,PendingIntent.FLAG_CANCEL_CURRENT);
And
Intent i = new Intent(context, TriggerNotification.class);
PendingIntent pi = PendingIntent.getBroadcast(context,System.currentTimeMillis(), i,PendingIntent.FLAG_CANCEL_CURRENT);
This way both the intents would be distinguished differently from each other and will get triggered.You can have any unique id instead of System.currentTimeMillis()

Creating Multiple Alarm?

Trying to create multiple Alarms using unique PendingIntent . However I am having trouble with this,
From MainActivity I press a button to set an Alarm, and the code for that is:
public void alarmSet(View view)
{
int idTime = (int) System.currentTimeMillis();
Intent intent = new Intent(MainActivity.this, AddAlarm.class);
intent.putExtra("pendInt",idTime);
startActivity(new Intent(MainActivity.this, AddAlarm.class));
}
Taking System time as unique id I am passing the value to the other activity from which I call the Broadcast to initiate alarm. Code for this Activity is:
Intent receive = getIntent();
pen = receive.getIntExtra("pendInt",0);
And here is the method in which I set the alarm.
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(AddAlarm.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, pen, alarmintent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
This works for single alarms , however it doesn't generate multiple alarms. What might be the possible reason? Any help will be appreciated. Do I need to post the Broadcast class as well ?
you are making Intent and putting extra but passing another Intent to startActivity()
just replace this
startActivity(new Intent(MainActivity.this, AddAlarm.class));
to this
startActivity(intent );

Starting up Service with AlarmManager , which already might be running

I need to run a service in time interval, for example every 2 minutes. I register it with AlarmManager, it works fine when the service stops itself before that 2 minutes is up, but there is a great chance it will take more than 2 minutes, in this case I'll need the service to be terminated and start up a new one, how can I do this?
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(), Sender.class);
PendingIntent pi = PendingIntent.getService(getApplicationContext(), 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000 * 30, pi);
Instead of starting service by AlarmManager use broadcast. Set AlarmManager to send some broadcast intent. Create your own BroadcastReceiver that will receive that intent and in onReceive method restart(stop and start) service.
//Start AlarmManager sending broadcast
Intent intent = new Intent(context, MyBroadcastReceiver.class); // explicit
peningIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30 * 1000, pendingIntent);
.
//BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(SynchronizationService.class.getName());
context.stopService(serviceIntent);
context.startService(serviceIntent);
}
}
.
//Register receiver in AndroidManifest.xml in Application tag
<receiver
android:name="com.example.MyBroadcastReceiver" >
</receiver>
You should write a login in onStartCommand itself.
Check if service is running or not using variable.
If its running call stopSelf method on service,then again call startservice for same service.
start a alarm manager services u have to use this code
Intent intent = new Intent(activity.this,Sender.class);
pendingIntent = PendingIntent.getBroadcast(activity.this.getApplicationContext(),1, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000 * 30, pendingIntent);
for stop this broadcast receiver use this code
Intent intent = new Intent(activity.this,Sender.class);
pendingIntent = PendingIntent.getBroadcast(activity.this.getApplicationContext(), 1,intent, 0);
pendingIntent.cancel() ;

Why an Alarm Broadcast receiver not receiving broadcast?

I am trying to start a service at specific intervals with help of a BroadcastReceiver. I have defined the receiver as an inner class in service itself as follows:
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("RTESPLDebug", "Recieved Broadcast!"); //Never appears in LogCat
//Intent i = new Intent(context, LocationUpdateService.class);
context.startService(intent);
}
};
I register the alarm receiver in service's onCreate():
context = super.getApplicationContext();
AlarmReceiver ar = new AlarmReceiver();
IntentFilter intfilter = new IntentFilter(Intent.ACTION_DEFAULT);
intfilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(ar, intfilter);
I first start the service from my first activity and then register a single alarm there:
Intent i = new Intent(context, LocationUpdateService.class);
context.startService(i);
// Schedule first alarm
int nextUpdateInterval = 30*1000; // Let first alarm be after 30 sec
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, LocationUpdateService.class);
intent.setAction(Intent.ACTION_DEFAULT);
intent.addCategory(Intent.CATEGORY_DEFAULT);
PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+nextUpdateInterval, pintent);
In the service I register for a single location update, and when I receive update (I do receive), I process it (I have debugged this, processing indeed completes without errors), and then I register next alarm in similar way as above:
int nextUpdateInterval = getNextUpdateInterval(); // Returns 30000
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, LocationUpdateService.class);
intent.setAction(Intent.ACTION_DEFAULT);
intent.addCategory(Intent.CATEGORY_DEFAULT);
PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+nextUpdateInterval, pintent);
Lots of code and a long questions.

Categories

Resources