Android IntentService詳解
一、IntentService簡介
IntentService是Service的子類,比普通的Service增加了額外的功能。先看Service本身存在兩個問題:
二、IntentService特征
三、使用步驟(詳情參考Service項(xiàng)目)
繼承IntentService類,并重寫onHandleIntent()方法即可;
MainActivity.Java文件
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startService(View source) { // 創(chuàng)建所需要啟動的Service的Intent Intent intent = new Intent(this, MyService.class); startService(intent); } public void startIntentService(View source) { // 創(chuàng)建需要啟動的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class); startService(intent); } } MyIntentService.java文件
public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } @Override protected void onHandleIntent(Intent intent) { // IntentService會使用單獨(dú)的線程來執(zhí)行該方法的代碼 // 該方法內(nèi)執(zhí)行耗時任務(wù),比如下載文件,此處只是讓線程等待20秒 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStart"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務(wù)執(zhí)行完成---"); } } MyService.java文件
public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { // 該方法內(nèi)執(zhí)行耗時任務(wù)可能導(dǎo)致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 (InterruptedException e) { e.printStackTrace(); } } } System.out.println("----耗時任務(wù)執(zhí)行完成---"); return START_STICKY; } } 運(yùn)行上述代碼,啟動MyIntentService的會使用單獨(dú)的worker線程,因此不會阻塞前臺的UI線程;而MyService會。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選