0
我正在編寫Android樣本服務,以檢查服務在關閉應用程序後是否停止。但在onStartCommand中,我已將START_NOT_STICKY作爲返回類型以避免自動重新啓動服務。爲什麼我的服務在Android中關閉我的應用程序時停止運行?
mycode的:
MainActivity.java
package com.example.sampleintentservice;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(MainActivity.this, TestService.class);
MainActivity.this.startService(i);
} }
TestService.java
package com.example.sampleintentservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class TestService extends Service
{
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}}
這是我上面的代碼,我不,當我明白關閉我的應用程序,服務正在停止。請幫助我,請建議我一些解決方案。
「小心:服務運行在其宿主進程的主線程中 - 服務不會創建它自己的線程,並且不會在單獨的進程中運行(除非您另有指定)這就意味着,如果你的服務要做任何CPU密集型工作或阻塞操作(如MP3播放或網絡連接),你應該在服務中創建一個新線程來完成這項工作。通過使用單獨的線程,你將降低應用程序不響應(ANR)錯誤的風險,並且應用程序的主線程可以保持專用於用戶與您的活動進行交互。「 – Fildor 2014-08-27 11:08:32
^^來自:http://developer.android.com/guide/components/services.html – Fildor 2014-08-27 11:10:35
你可以請我建議,我怎麼可以在我的服務中使用線程 – user3976029 2014-08-27 11:10:36