Android中使用IntentService執行背景工作

來源:互聯網
上載者:User

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:

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.