請先看有關IntentService官網介紹,另外這裡和這裡也 有詳細說明原理。這裡用程式實作,並發現,一般的Service執行完後並沒有停止,在 Settings->Applications->Running services中可以發現依然存在,但是如果程式改用IntentService,則會發現執行程式後,在 Settings->Applications->Running services 是看不到的。
程式有2個檔案如下:
Main.java = 一個Activity的主畫面,按下畫面的按鈕可以呼叫Service
OriginalService.java = 繼承IntentService
Main.java 如下:
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn1);
OnClickListener lis = new OnClickListener() {
public void onClick(View v) {
Intent it = new Intent();
it.setClass(Main.this, OriginalService.class);
startService(it);
}
};
btn.setOnClickListener(lis);
}
}
//OriginalService.java 如下:
public class OriginalService extends IntentService {
//這個constructor一定要寫,不然在runtime的時候,會出現
// java.lang.InstantiationException 的錯誤
public OriginalService(){
super("OriginalService");
}
public OriginalService(String name) {
super(name);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("gill", "onStartCommand, the hashcode = " + this.toString());
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
//這裡寫上任何想要在背景耗時的作業,比如網路下載,讀取資料庫,播放音樂音效…
}
}
程式有2個檔案如下:
Main.java = 一個Activity的主畫面,按下畫面的按鈕可以呼叫Service
OriginalService.java = 繼承IntentService
Main.java 如下:
public class Main extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn1);
OnClickListener lis = new OnClickListener() {
public void onClick(View v) {
Intent it = new Intent();
it.setClass(Main.this, OriginalService.class);
startService(it);
}
};
btn.setOnClickListener(lis);
}
}
//OriginalService.java 如下:
public class OriginalService extends IntentService {
//這個constructor一定要寫,不然在runtime的時候,會出現
// java.lang.InstantiationException 的錯誤
public OriginalService(){
super("OriginalService");
}
public OriginalService(String name) {
super(name);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("gill", "onStartCommand, the hashcode = " + this.toString());
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
//這裡寫上任何想要在背景耗時的作業,比如網路下載,讀取資料庫,播放音樂音效…
}
}
沒有留言:
張貼留言