2012-04-06 95 views
1

我需要在刪除數據庫之前停止一對服務。服務正在訪問數據庫,如果它們沒有停止,應用程序將崩潰。我可以同步停止服務嗎?

像這樣:

stopService(new Intent(CurrentClass.this, FirstService.class)); 
stopService(new Intent(CurrentClass.this, SecondService.class)); 
CurrentClass.this.deleteDatabase(MyDatabaseHelper.DATABASE_NAME); 

據我所知,問題是,stopService是異步的。在我的數據庫被刪除之前,如何強制我的服務停止?

謝謝!

回答

2

據我所知,被銷燬的服務的確切時間取決於Android,並且可能不是直接的..所以請牢記這一點......我認爲最好是您檢查您的服務if你的數據庫是可用的 ..然後訪問它...如果你想..你不應該做這種檢查,如果DATABSE是可用的,總是,在服務......你叫那麼之前

stopService(new Intent(CurrentClass.this, FirstService.class)); 
stopService(new Intent(CurrentClass.this, SecondService.class)); 

廣播一個意圖,要求服務停止,並在您的服務中實現一個監聽器,並在該監聽器的接收者啓動檢查數據庫是否可用的方法....像這樣..例如..

//this is in your service.. 
bool stopping=false 
....... 

if(stopping) 
    { 
    //check if your databse is available and access it 
    } 
else{ 
    //access your database directly.. 
    } 

,並在自己的廣播接收器

@Override 
    public void onReceive(Context context, Intent intent){ 
    stopping=true; 
    } 
+0

我得到了它的多一點簡單地使用這種思想工作的的onReceive。我只是檢查我的數據庫是否打開,然後在關鍵位置訪問它,這對我來說很合適。 – Brianide 2012-04-07 02:34:11

相關問題