问题
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.
回答1:
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.
回答2:
On the Alarm manager, simply pass getApplicationContext as a parameter to the helper contructor.
来源:https://stackoverflow.com/questions/12256434/passing-values-using-intent-extras-in-alarm-manager-in-android