Android---43---Service之IntentService,androidintent
首先說一下Service本身存在的兩個問題:
1.Service不會專門啟動一條新的線程,Service與它所在應用位於同一個進程中。
2.Service也不是專門一條新的線程,所以不應該在Service中處理耗時的任務。
IntentService正好彌補了這兩個不足:
IntentService可以處理非同步請求的Service。
IntentService將會使用隊列來管理請求Intent,每當用戶端代碼通過Intent請求啟動IntentService時,IntentService
會將該Intent加入到隊列中,然後開啟一條新的worker線程來處理該Intent。在完成的時候會自動停止,不用手動去停止它。
IntentService的特點:
IntentService會建立單獨的worker線程來處理所有的Intent請求
IntentService會建立單獨的worker線程來處理onHandleIntent方法實現的代碼,因此開發人員不需要處理多線程問題
當所有的請求處理完成後,IntentService會自動停止,無需調用stopSelf方法來停止該Service
為Service的onBind方法提供了預設實現,預設該方法返回null
為Service的onStartCommand方法提供了預設實現,該實現會將Intent添加到隊列中。
所以在繼承IntentService時,不需要onBind onStartCommand 方法,只要實現onHandleIntent方法即可
public class IntentServiceTest extends Activity{@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}public void startService(View source){// 建立需要啟動的Service的IntentIntent intent = new Intent(this, MyService.class);// 啟動ServicestartService(intent);}public void startIntentService(View source){// 建立需要啟動的IntentService的IntentIntent intent = new Intent(this, MyIntentService.class);// 啟動IntentServicestartService(intent);}}
上面Activity的兩個時間處理方法中分別啟動MyService與MyIntentService。
MyService.java:
public class MyService extends Service{@Overridepublic IBinder onBind(Intent intent){return null;}@Overridepublic int onStartCommand(Intent intent, int flags, int startId){// 該方法內執行耗時任務可能導致ANR(Application Not Responding)異常long endTime = System.currentTimeMillis() + 20 * 1000;System.out.println("onStart");while (System.currentTimeMillis() < endTime){synchronized (this){try{wait(endTime - System.currentTimeMillis());}catch (Exception e){}}}Toast.makeText(getApplicationContext(), "耗時任務執行完成", 1).show();System.out.println("---耗時任務執行完成---");return START_STICKY;}}
MyIntentService.java:
public class MyIntentService extends IntentService{public MyIntentService(){super("MyIntentService");}// IntentService會使用單獨的線程來執行該方法的代碼@Overrideprotected void onHandleIntent(Intent intent){// 該方法內可以執行任何耗時任務,比如下載檔案等,此處只是讓線程暫停20秒long endTime = System.currentTimeMillis() + 20 * 1000;System.out.println("onStart");while (System.currentTimeMillis() < endTime){synchronized (this){try{wait(endTime - System.currentTimeMillis());}catch (Exception e){}}}System.out.println("---耗時任務執行完成---");Toast.makeText(getApplicationContext(), "耗時任務執行完成", 0).show();}}