Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing values using intent extras in Alarm Manager in android

I want to know if this code will work(I cannot try it out right now. Moreover, I have a few doubts that have to be cleared).

Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("user",global.getUsername());
intent.puExtra("password",global.getPassword);
PendingIntent sender = PendingIntent.getBroadcast(context, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
Log.v("inside log_run", "new service started");
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, IMMEDIATELY,60000,sender);
finish();

As you can see, this code starts an AlarmManager with setRepeating(). If you see the intent(actually the pending intent) passed on to the BroadcastReceiver, there are two extras that are passed on. These are global variables that live as long as the Application is running. But this AlarmManager is meant to be run in the background (that is application will be alive only for the first few calls of the of the alrmamanager to the broadcast recevier)
My Question
Will AlarmManager make a copy of the global variables(the username and password) and maintain this copy to be passed along with the intent (as extras)? Or will it reference the global variables (in the process pass null as the extra when the global variables become null)? Because, these values will be used in the broadcast receiver.

like image 947
Ashwin Avatar asked Dec 29 '25 06:12

Ashwin


1 Answers

I can see problems arising from this method. What I would do is store your two variables in a SharedPrefs file and access them from the BroadcastReciever directly. SharedPrefs values persist while "global variables" in Android do not.

like image 120
James Fazio Avatar answered Dec 31 '25 21:12

James Fazio