我有一個服務綁定在我的活動與ServiceConnection。 服務在創建活動時開始並停在我的BroadcastReceiver類中,並且效果很好。現在,我想在一段時間後停止服務。正在嘗試我的Service類中的TimerTask,但似乎沒有正常工作。停止服務與Android中的Activity中的ServiceConnection綁定的最佳方法?
任何建議或解決方案,將不勝感激。
謝謝。
我有一個服務綁定在我的活動與ServiceConnection。 服務在創建活動時開始並停在我的BroadcastReceiver類中,並且效果很好。現在,我想在一段時間後停止服務。正在嘗試我的Service類中的TimerTask,但似乎沒有正常工作。停止服務與Android中的Activity中的ServiceConnection綁定的最佳方法?
任何建議或解決方案,將不勝感激。
謝謝。
計時器也被視爲獨立的Thread.so上下文可能會改變,當你試圖停止服務。我的解決方案是獲取當前服務的Pid和殺死服務使用Pid。 android:process屬性將在androidmanifest.xml中指定。
Process process = Runtime.getRuntime()。exec(「kill pid」); InputStream is = process.getInputStream();
此代碼正常工作。試一次
聲明靜態在您的應用程序:在應用程序的
static Intent local_Intent;
上創建分配一個新的Intent的服務,並綁定到local_Intent:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
local_Intent = new Intent(this, yourAppService.class);
}
分配給local_Intent是記住,因爲local_Intent是靜態的 當你想在你的應用程序啓動服務
startService(local_Intent);
當您想停止您的應用中的服務時
stopService(local_Intent);