Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use requestCode in PendingIntents

I'm trying to implement a reminder app.I have all reminder details stored in sqlite database such id,title,dateInfo,timeInfo etc.

I want to notify the user at appropriate time about the reminder for which i would be using AlarmManager.

Is the below given steps feasible.

Providing id of row as requestCode in pendentingIntents. Then setting an alarm that would call a service once triggered. The service would use this id to get data from the database.

If this is feasible can anyone pls provide me with a code snippet.

Any help would be highly appreciated

like image 728
Abhijeet Sonawane Avatar asked Nov 04 '22 01:11

Abhijeet Sonawane


2 Answers

You can simply put your rowId as extra in the called intent. Here's a code snippet that might help:

Intent i = new Intent(this, YourServiceOrActivity.class);
i.putExtra("rowId", rowId);
PendingIntent pi = PendingIntent.getActivity(this, 123123, i, 0); //Notice the random requestCode '123123' as it doesn't matter, yet.

And you can set the alarm as follows:

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, AlarmManager.INTERVAL_DAY, pi); 
//Set the alarm to wake up the device after one day calling the pending intent 'pi'.

Finally you can get the rowId from the intent (onCreate() for example if intent is an Activity) when called as follows:

Bundle extras = getIntent().getExtras();
if (extras != null) rowId = extras.getInt("rowId", 0); //Be safe

Hope this helps.

like image 122
salrawaf Avatar answered Nov 14 '22 23:11

salrawaf


As others mentioned I would put rowId as an extra, BUT do not be mistaken - as wroten in PendingIntent doc, intents are distinct as below:

If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent. filterEquals, or different request code integers supplied to getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).

So if you put your request with the same id for all intents for the same row, with different data, you can get lost with obsolete/repeated data issues.

like image 43
Witold Kupś Avatar answered Nov 15 '22 01:11

Witold Kupś