Android中使用IntentService執行背景工作
IntentService提供了一種在後台線程中執行任務的方式,適合處理執行時間較長的背景工作。
優點:
(1)IntentService運行在單獨的線程中,不會阻塞UI線程
(2)IntentService不受生命週期的影響
缺點:
(1)不能與UI直接進行互動,可以用Broadcast
(2)順序執行請求,第二個請求只有在第一個請求執行完以後才能執行
(3)請求不能被中斷
使用IntentService的步驟:
(1)在Activity中通過startService啟動service,並傳遞參數。
(2)Service中接收參數,做耗時的處理,處理完畢,發送Broadcat,並把處理結果傳遞出來
(3)Activity中註冊BroadcastReceiver,監聽廣播,更新UI。
看一個例子:
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btn = (Button) this.findViewById(R.id.btn);btn.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {//通過startService啟動service,並傳遞參數。Intent mServiceIntent = new Intent(MainActivity.this,RSSPullService.class);mServiceIntent.setData(Uri.parse(http://www.baidu.com/));MainActivity.this.startService(mServiceIntent);}});//註冊BroadcastReceiver,監聽廣播IntentFilter statusIntentFilter = new IntentFilter(Constants.BROADCAST_ACTION); // Sets the filter's category to DEFAULT statusIntentFilter.addCategory(Intent.CATEGORY_DEFAULT);DownloadStateReceiver mDownloadStateReceiver = new DownloadStateReceiver();// Registers the DownloadStateReceiver and its intent filtersLocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver, statusIntentFilter);}private class DownloadStateReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {String data = intent.getStringExtra(Constants.EXTENDED_DATA);Log.e(test, data);Toast.makeText(context, data, Toast.LENGTH_SHORT).show();}}}
public class RSSPullService extends IntentService {public RSSPullService() {super(RSSPullService);}@Overrideprotected void onHandleIntent(Intent workIntent) {//接收參數,做耗時的處理,處理完畢,發送BroadcatString localUrlString = workIntent.getDataString();String data = download(localUrlString);Intent localIntent = new Intent(Constants.BROADCAST_ACTION); // Puts the status into the IntentlocalIntent.putExtra(Constants.EXTENDED_DATA, data); // Broadcasts the Intent to receivers in this app. LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);}private String download(String localUrlString){try{URL url = new URL(localUrlString);HttpURLConnection conn = (HttpURLConnection)url.openConnection();InputStream in = conn.getInputStream();ByteArrayOutputStream out = new ByteArrayOutputStream();byte[] buff = new byte[1024];int len = 0;while((len = in.read(buff)) != -1){out.write(buff,0,len);}in.close();return new String(out.toByteArray());}catch(Exception e){e.printStackTrace();return ;}}}
public class Constants {// Defines a custom Intent actionpublic static final String BROADCAST_ACTION = com.example.android.threadsample.BROADCAST;// Defines the key for the status extra in an Intentpublic static final String EXTENDED_DATA_STATUS = com.example.android.threadsample.STATUS;public static final String EXTENDED_DATA = com.example.android.threadsample.DATA;}
AndroidManifest.xml: