我有一個應用,該應用在背景(也當屏幕已swiched關閉)做的東西在一個服務。我在以下代碼的Activity中啓動該服務。服務與AlarmManager
Intent i=new Intent(this, AppService.class);
i.putExtra(AppService.VOL_ALM, amanager.getStreamVolume(amanager.getStreamVolume(AudioManager.STREAM_ALARM)));
PendingIntent pi = PendingIntent.getService(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 *60, pi);
在trhe服務的代碼看起來是這樣的:
public int onStartCommand(Intent intent, int flags, int startId) {
test = intent.getIntExtra(VOL_ALM, 0);
timer = new Timer("TweetCollectorTimer");
timer.schedule(updateTask, 0, 15 * 1000L);
return(START_NOT_STICKY);
}
在服務我必須要改變的變量「test」,並使用它。但我總是失去變量的值,因爲onStartCommand有時會執行。我嘗試存儲具有首選項的變量,但在啓動服務時我還需要變量的原始值。 最好的方法是從方法中的意圖改變數據「VOL_ALM」。但那有可能嗎?
在此先感謝
你能堅持一個數組的SharedPreferences,並用'System.arraycopy(...)'重建。 (0 - 1 VOL_ARM,1 - 2 VOL_ARM)... O(N)...誒.. :(用它來箱前/重新創建每個「報警事件」列表中,我會考慮的架構變化 - 就像IPC消息和與該消息的服務交易。 – bgs