2012-10-22 137 views
2

我有一個問題,實施什麼應該是一個簡單的例子與服務。 繼Android開發人員計劃後,我設法綁定到服務。該服務完美運作。android服務啓動時間

我想實現的是服務的起始日期。我在

public class MyService extends Service { 

    private Date _firstActivation= new Date(); 
    .... 
    .... 
    public Date GetFirstActivation() { 
    return _firstActivation; 
} 
} 

在結合我OnStart方法中有一個基本實現服務的主要活動

// Check if the Service is running and if it's running let's bind to the service through ServiceConnectionClass 
    if (((MyApplication)getApplication())._serviceIsRunning) 
    { 
     Intent intent = new Intent(this, MyService.class); 
     bindService(intent, mConnection, 0); 
     _startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 
    } 
    else { 
     _startingTime_TV.setText("Service Not Started"); 
    } 

其中_myService是爲MyService和mConnection是ServiceConnection ...

現在我期望的是,一旦服務第一次啓動,每次我停止活動(同時解除綁定)並重新啓動活動(並同時綁定)我可以看到的textview始終是相同的開始時間。

什麼情況,該時間變化每次我重新啓動活動...

沒有人有線索?

回答

1

Service的生命週期決定: - 如果通過bindService啓動,Service時解除綁定 停止 - 如果通過startService啓動,它通過stopService或者Android操作系統停止想這

所以第一總是:始終通過startService開始您的服務,然後綁定到它。 在你的約束你可以這樣做:_startingTime_TV.setText(_df.format(_myService.GetFirstActivation())); 因爲在bindService(intent, mConnection, 0);之後,你還沒有約束。你必須等待回調:onServiceConnected(功能ServiceConnection