Android中使用IntentService執行背景工作,androidintent
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:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.intentservicedemo" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" /> <!-- Requires this permission to download RSS data from Picasa --> <uses-permission android:name="android.permission.INTERNET" /> <!-- Defines the application. --> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name="com.example.android.intentservicedemo.MainActivity" android:label="@string/activity_title" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <!-- No intent filters are specified, so android:exported defaults to "false". The service is only available to this app. --> <service android:name="com.example.android.intentservicedemo.RSSPullService" android:exported="false"/> </application></manifest>
參考:http://developer.android.com/training/run-background-service/index.html
android activity,intent,service是什關係?
intent是activity和service的橋樑,通訊員,activity主要操作顯示介面,service在後台運行,適合長時間運行,如下載,聽歌等。。
ANDroid中IntentService有何優點
IntentService是一個通過Context.startService(Intent)啟動可以處理非同步請求的Service,使用時你只需要繼承IntentService和重寫其中的onHandleIntent(Intent)方法接收一個Intent對象,在適當的時候會停止自己(一般在工作完成的時候). 所有的請求的處理都在一個背景工作執行緒中完成,它們會交替執行(但不會阻塞主線程的執行),一次只能執行一個請求。
這是一個基於訊息的服務,每次啟動該服務並不是馬上處理你的工作,而是首先會建立對應的Looper,Handler並且在MessageQueue中添加的附帶客戶Intent的Message對象,當Looper發現有Message的時候接著得到Intent對象通過在onHandleIntent((Intent)msg.obj)中調用你的處理常式.處理完後即會停止自己的服務.意思是Intent的生命週期跟你的處理的任務是一致的.所以這個類用下載任務中非常好,下載任務結束後服務自身就會結束退出.