2012-10-23 84 views
0

我有一個應用,該應用在背景(也當屏幕已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」。但那有可能嗎?

在此先感謝

+0

你能堅持一個數組的SharedPreferences,並用'System.arraycopy(...)'重建。 (0 - 1 VOL_ARM,1 - 2 VOL_ARM)... O(N)...誒.. :(用它來箱前/重新創建每個「報警事件」列表中,我會考慮的架構變化 - 就像IPC消息和與該消息的服務交易。 – bgs

回答

1

儲存在SharedPreferences兩個值?這是堅持價值觀的可接受方法。

+0

當我重新啓動我從意向需要的數據服務的問題。但是,當服務在後臺運行onStartCommand()有時被稱爲。我不知道從開始的區別該服務在後臺運行,因爲onStartCommand被稱爲在這兩種情況下 – user1390816

+1

@ user1390816:。您的服務的負荷'的onCreate(從後備存儲器中的數據)' – CommonsWare

+0

非常感謝你,我認爲這應該工作,我刪除onCreate()並在onStartCommand()中加載它,我會發布如果它工作。 – user1390816