稍微翻譯理一理,這裡主要是說IntentService使用隊列的方式將請求的Intent排入佇列,然後開啟一個worker thread(線程)來處理隊列中的Intent,對於非同步startService請求,IntentService會處理完成一個之後再處理第二個,每一個請求都會在一個單獨的worker thread中處理,不會阻塞應用程式的主線程,這裡就給我們提供了一個思路,如果有耗時的操作與其在Service裡面開啟新線程還不如使用IntentService來處理耗時操作。下面給一個小例子:
1.Service:
- package com.zhf.service;
-
- import Android.app.Service;
- import Android.content.Intent;
- import Android.os.IBinder;
-
- public class MyService extends Service {
-
- @Override
- public void onCreate() {
- super.onCreate();
- }
-
- @Override
- public void onStart(Intent intent, int startId) {
- super.onStart(intent, startId);
- //經測試,Service裡面是不能進行耗時的操作的,必須要手動開啟一個背景工作執行緒來處理耗時操作
- System.out.println("onStart");
- try {
- Thread.sleep(20000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("睡眠結束");
- }
-
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- }
|
2.IntentService:
- package com.zhf.service;
-
- import Android.app.IntentService;
- import Android.content.Intent;
-
- public class MyIntentService extends IntentService {
-
- public MyIntentService() {
- super("yyyyyyyyyyy");
- }
-
- @Override
- protected void onHandleIntent(Intent intent) {
- // 經測試,IntentService裡面是可以進行耗時的操作的
- //IntentService使用隊列的方式將請求的Intent排入佇列,然後開啟一個worker thread(線程)來處理隊列中的Intent
- //對於非同步startService請求,IntentService會處理完成一個之後再處理第二個
- System.out.println("onStart");
- try {
- Thread.sleep(20000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- System.out.println("睡眠結束");
- }
- }
|
測試主程式:
- package com.zhf.service;
-
- import Android.app.Activity;
- import Android.content.Intent;
- import Android.os.Bundle;
-
- public class ServiceDemoActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- startService(new Intent(this,MyService.class));//主介面阻塞,最終會出現Application not responding
- //連續兩次啟動IntentService,會發現應用程式不會阻塞,而且最重的是第二次的請求會再第一個請求結束之後運行(這個證實了IntentService採用單獨的線程每次只從隊列中拿出一個請求進行處理)
- startService(new Intent(this,MyIntentService.class));
- startService(new Intent(this,MyIntentService.class));
- }
- }
|