安卓的IntentService的用法

xiaoxiao2021-02-28  63

普通的Service存在两个问题:1.不会启动一个单独的进程,Service与它所在应用位于同一个进程;2。Service不是一条新的线程,所以若在Service中处理耗时任务会带来ANR的问题。使用IntentService时不会产生这样的情况,它将耗时任务放在onHandleIntent()中执行,这样,应用还能得以相应。

MainActivity.java

:

package com.example.wanglunhui.intentservicetest; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void startService(View source) { // 创建需要启动的Service的Intent Intent intent = new Intent(this, MyService.class);//启动Service的时候,程序不能相应其他的动作,不能点击其他按钮,不能启动新线程 // 启动Service startService(intent); } public void startIntentService(View source) { // 创建需要启动的IntentService的Intent Intent intent = new Intent(this, MyIntentService.class);//启动IntentService的时候,程序还能相应其他动作,仍能点击其他按钮 // 启动IntentService startService(intent);//IntentService也是用startService即可 } } Service.java: package com.example.wanglunhui.intentservicetest; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public 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) { } } } System.out.println("---耗时任务执行完成---"); return START_STICKY; } } IntentService.java: package com.example.wanglunhui.intentservicetest; import android.app.IntentService; import android.content.Intent; public class MyIntentService extends IntentService//继承了IntentService类,只需重写onHandleIntent方法,在里面做耗时任务。不需实现onBind()和 { //onStartCommand()方法。 public MyIntentService() { super("MyIntentService"); } // IntentService会使用单独的线程来执行该方法的代码 @Override protected void onHandleIntent(Intent intent) { // 该方法内可以执行任何耗时任务,比如下载文件等,此处只是让线程暂停20秒 long endTime = System.currentTimeMillis() + 20 * 1000; System.out.println("onStartCommand"); while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } System.out.println("---耗时任务执行完成---"); } }

转载请注明原文地址: https://www.6miu.com/read-200246.html

最新回复(0)