Service是Android中的四大組件之一,它是在後臺運行的,被用來處理比較耗時或長時間運行的操作。現在我們有一個需求:下載一個大的文件。根據Service的特性,我們很容易想到用開啓一個Service來進行下載。Service有兩種啓動方式,startService和bindService,那麼問題來了,我們用哪種方式啓動呢?方案1:用一個程序組件startService,用該方法啓動Service後,Service會一直在後臺運行,即使該組件被終止,Service仍然繼續運行,但是當文件下載完成,我們不希望Service繼續運行,比較消耗資源。方案2:用一個程序組件bindService,用該方法綁定一個Service,如果該組件被終止,Service也會停止運行,我們不希望用戶點擊完下載就不能進行其他操作。那麼該怎麼辦呢?接下來就是IntentService表現的時候了。IntentService是Service的一個子類,他本質上就是一個Service,它的特點是在完成操作後會自動的停止,並且它會自動開啓一個線程。使用的時候我們編寫一個類繼承IntentService,同時,我們需要在清單文件中註冊,如同Service。
public class MyIntentService extends IntentService {
public MyIntentService() {
this("MyThread");
}
// IntentService會自動建立一個子線程,並在其中執行,name爲子線程的名稱
public MyIntentService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
// 要做的操作寫在這個方法中,方法執行結束執行onDestory(),可以通過Intent來接受傳遞過來的數據
@Override
protected void onHandleIntent(Intent intent) {
String extra = intent.getStringExtra("url");
System.out.println(extra);
// 模擬耗時操作,注意不用開啓子線程
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ThreadName:" + Thread.currentThread().getName());
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("onDestory");
}
}
這樣一個IntentService就完成了,接下來開始編寫調用他的組件。
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt = (Button) findViewById(R.id.bt);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MyIntentService.class);
// 傳遞的數據
intent.putExtra("url", "http://www.baidu.com");
startService(intent);
}
});
}
}
我們在Activity裏面添加了一個Button,點擊這個Button之後開啓一個IntentService,並通過Intent傳遞數據。可以看出IntentService使用起來還是很簡單的。