![](/img/trans.png)
[英]When will service stop if i don't call stopService() or stopSelf() methods
[英]Where to call stopService() to ensure a service is stopped?
我知道以前有人問過很多關於如何停止服務的問題,但我沒有找到一個解決我的特定問題的問題。
在我的應用程序中,我有許多與一個中央服務通信的活動。 對於每個活動,我在其 onResume() 方法中調用 bindService() 並在其 onPause() 方法中調用 unbindService()。 我遇到的問題是,每次我在兩個活動之間切換時,服務都會被銷毀,然后從頭開始重新創建。
為了解決這個問題,我考慮在 onCreate() 中調用 startService(),以確保服務保持活動狀態。
我的問題是,我應該將 stopService()-Method 放在哪里以確保在離開應用程序時調用它? 或者,當我在兩個活動之間切換時,是否有另一種方法可以保持服務運行,而不依賴 startService()?
請參閱android service startService() 和 bindService()以獲得全面的答案。
這就是我停止和啟動服務的方式
檢查此鏈接以獲取更多詳細信息。
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
break;
}
}
在服務 class 中:
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
快樂編碼!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.