Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 IntentService 中執行後台任務的完整實踐

編輯:關於 Android 程式設計

除非我們明確為某個操作指定線程,否則絕大多數運行在 UI 界面上的任務,都跑在一個叫做 UI Thread 的特殊線程裡。這其中潛藏著隱患:一旦 UI 上出現耗時操作,就可能拖累界面的響應性能。界面卡頓不僅容易惹惱用戶,甚至可能觸發系統的 ANR(無響應)錯誤。為了規避這類問題,Android Framework 提供了幾個類,幫助我們把耗時操作搬到後台線程中執行,其中最常用的莫過於 IntentService。

創建 IntentService

IntentService 為「在單一後台線程中執行任務」提供了一種直截了當的實現方式。它能勝任耗時任務,並確保不影響 UI 的響應性;同時,由於它的執行不受 UI 生命周期牽制,還能像 AsyncTask 那樣保證任務順利跑完。

不過,IntentService 也有幾個明顯的局限:

它無法直接與 UI 交互,若想把執行結果體現在界面上,需要主動把結果回傳給 Activity。

它內部的工作隊列是順序執行的:若一個任務正在執行,此時再發來新任務,新任務只能排隊等待,直到前一個任務跑完才會開始。

正在執行的任務無法中途打斷。

儘管存在這些限制,在大多數場景下,IntentService 仍然是執行簡單後台任務的理想選擇。

Step 1: 為你的 App 創建一個 IntentService 組件。做法是自定義一個繼承自 IntentService 的新類,並重寫 onHandleIntent() 方法,如下所示:

 public class RSSPullService extends IntentService { @Override protected void onHandleIntent(Intent workIntent) { // 這裡可以得到傳進來的intent,就可以獲得intent所攜帶的數據 String dataString = workIntent.getDataString(); ... // 對獲得的數據進行操作,比如一些耗時的網絡操作 ... } }

注意:普通 Service 的其他回調(如 onCreate()、onStartCommand())會被 IntentService 自動調用,因此應避免重寫它們。

Step 2:在 Manifest 文件中聲明這個 IntentService,添加如下條目:

 ...     ... 

注意, 標簽並沒有包含任何 intent-filter。這是因為向 IntentService 派發任務的 Activity 使用的是顯式 Intent,本就不需要 filter。這也意味著,只有同一個 App(或共用同一 UserID 的組件)才能訪問到這個 Service。

至此,你已經擁有一個基本的 IntentService 類,可以通過構造 Intent 對象向它發送操作請求了。

創建任務請求並發送到 IntentService

要創建任務請求並發送給 IntentService,需要這樣做:先構造一個顯式 Intent,把請求數據塞進去,然後調用 startService() 方法把任務發送出去。代碼示例如下:

創建一個新的顯式 Intent 用來啟動 IntentService:

 /* * 創建一個Intent來啟動RSSPullService,把一個鏈接存放進intent中 */ Intent mServiceIntent = new Intent(getActivity(), RSSPullService.class); mServiceIntent.setData(Uri.parse(dataUrl));

執行 startService() 開啟服務:

 getActivity.startService(mServiceIntent);

注意:你可以在 Activity 或 Fragment 的任何位置發送任務請求。例如,先獲取用戶輸入,再在按鈕點擊或類似手勢的回調方法裡發送請求。

一旦執行 startService(),IntentService 便會在自己的 onHandleIntent() 中開始執行任務;任務結束後,不需要調用 stopService() 去停止它,因為 IntentService 會自動停止自身。下一步,就是把任務的執行結果回傳給發起請求的 Activity 或 Fragment。

利用 IntentService 將執行結果返回給 Activity 或 Fragment

下面用一個實例說明 IntentService 的整體工作步驟:

(1)在 Activity 中通過 startService 啟動 service,並傳遞參數;

(2)Service 接收參數,做耗時處理,處理完畢後發送 Broadcast,並把結果帶出來;

(3)Activity 註冊 BroadcastReceiver,監聽廣播並更新 UI。

Step 1:創建一個 IntentService,接收參數。

RSSPullService.java

 public class RSSPullService extends IntentService { // public static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST"; //構造方法必須重寫 public RSSPullService() { super("RSSPullService"); } @Override protected void onHandleIntent(Intent workIntent) { //接收參數,做耗時的處理,處理完畢,發送Broadcat //將數據打印出來 Log.i(TAG,dataString); //接收到數據,做耗時處理 String result = downloadHtml(dataString); Log.i("result",result); } ... }

Step 2:在 MainActivity 中通過 startService 啟動 IntentService,並傳遞參數。

MainActivity.java

 public class MainActivity extends AppCompatActivity { MyReceiver receiver = new MyReceiver(); TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); regist(); bindView(); } private void bindView() { mTextView = (TextView)this.findViewById(R.id.textView); Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override //創建一個顯示Intent Intent serviceIntent = new Intent(MainActivity.this,RSSPullService.class); //將百度網址傳入Intent serviceIntent.setData(Uri.parse("https://www.baidu.com")); //啟動服務 startService(serviceIntent); } }); } ... }

Step 3:在 MainActivity 中註冊廣播。這裡我們借助 LocalBroadcastManager 來註冊並監聽廣播。

MainActivity.java

 private void regist() { IntentFilter intentFilter = new IntentFilter(RSSPullService.BROADCAST_ACTION); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter); } //取消注冊 protected void onDestroy() { super.onDestroy(); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); }

Step 4:在 service 中處理耗時操作,發送 Broadcast 並把結果帶出來。

RssPullService.java

 public class RSSPullService extends IntentService { private static final String TAG = "RSSPullService"; public static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS"; private LocalBroadcastManager mLocalBroadcastManager; ... protected void onHandleIntent(Intent intent) { ... //將耗時操作的結果放進Intent,調用LocalBroadcastManager.sendBroadcast將intent傳遞回去 Intent localIntent = new Intent(BROADCAST_ACTION); localIntent.putExtra(EXTENDED_DATA_STATUS,result); mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); mLocalBroadcastManager.sendBroadcast(localIntent); } ... //處理耗時任務的方法 private String downloadHtml(String dataString) { try { URL url = new URL(dataString); 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(); Log.i("html",out.toByteArray().toString()); return new String(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); return ""; } } }

Step 5:在 Activity 中創建廣播接收器,接收廣播並更新 UI。

MainActivity.java

  private class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String data = intent.getStringExtra(RSSPullService.EXTENDED_DATA_STATUS); Log.i("test", data); mTextView.setText(data); } }

最後別忘了加上網絡權限:

  

執行結束後,效果圖如下:

下面把幾個主要類的完整代碼一併貼出:

MainActivity.java:

 public class MainActivity extends AppCompatActivity { MyReceiver receiver = new MyReceiver(); TextView mTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); regist(); bindView(); } private void regist() { IntentFilter intentFilter = new IntentFilter(RSSPullService.BROADCAST_ACTION); intentFilter.addCategory(Intent.CATEGORY_DEFAULT); LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter); } private void bindView() { mTextView = (TextView)this.findViewById(R.id.textView); Button button = (Button)this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent serviceIntent = new Intent(MainActivity.this,RSSPullService.class); serviceIntent.setData(Uri.parse("https://www.baidu.com")); startService(serviceIntent); } }); } private class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String data = intent.getStringExtra(RSSPullService.EXTENDED_DATA_STATUS); Log.i("test", data); mTextView.setText(data); } } protected void onDestroy() { super.onDestroy(); LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver); } } 

RssPullService.java:

 public class RSSPullService extends IntentService { public static final String BROADCAST_ACTION = "com.example.android.threadsample.BROADCAST"; private static final String TAG = "RSSPullService"; public static final String EXTENDED_DATA_STATUS = "com.example.android.threadsample.STATUS"; private LocalBroadcastManager mLocalBroadcastManager; private ResponseReceiver receiver; public RSSPullService() { super("RSSPullService"); } @Override protected void onHandleIntent(Intent intent) { String dataString = intent.getDataString(); Log.i(TAG,dataString); String result = downloadHtml(dataString); Log.i("result",result); Intent localIntent = new Intent(BROADCAST_ACTION); localIntent.putExtra(EXTENDED_DATA_STATUS,result); mLocalBroadcastManager = LocalBroadcastManager.getInstance(this); mLocalBroadcastManager.sendBroadcast(localIntent); } private String downloadHtml(String dataString) { try { URL url = new URL(dataString); 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(); Log.i("html",out.toByteArray().toString()); return new String(out.toByteArray()); } catch (Exception e) { e.printStackTrace(); return ""; } } } 

AndroidManifest.xml:

  ...      
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved