Android应用软件开发

194课时
1.7K学过
8分

课程评价 (0)

请对课程作出评价:
0/300

学员评价

暂无精选评价
3分钟

4.2.3 相关知识

相关知识

在service中启动一个耗时任务,则会引发ANR(Application No Response)异常,而IntentService则不会出现ANR异常。

在Android中,应用的响应性被活动管理器(Activity Manager)和窗口管理器(Window Manager)这两个系统服务所监视。当用户触发了输入事件(如键盘输入,点击按钮等),如果应用5秒内没有响应用户的输入事件,那么,Android会认为该应用无响应,便弹出ANR对话框。

Service在主线程中运行,若执行一个耗时任务,则会导致输入事件无法得到及时响应,就会引起ANR异常。解决这个问题的方法是使用IntentService,IntentService会新启动一个线程执行,不会堵塞主线程。

 IntentService,可以看做是Service和HandlerThread的结合体,在完成了使命之后会自动停止,适合需要在工作线程处理UI无关任务的场景。IntentService有如下特点:

  • l IntentService 是继承自 Service 并处理异步请求的一个类,在 IntentService 内有一个工作线程来处理耗时操作。
  • l 当任务执行完后,IntentService 会自动停止,不需要我们去手动结束。
  • l 如果启动 IntentService 多次,那么每一个耗时操作会以工作队列的方式在 IntentService 的 onHandleIntent 回调方法中执行,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推,执行完自动结束。
  • l 所有请求都在一个单线程中,不会阻塞应用程序的主线程(UI Thread),同一时间只处理一个请求。

在实现IntentService时,只需要重写onHandleIntent()方法即可,其他的方法可用默认方法。如表4-2-13所示,只实现intentServiceTest类后,程序依然完成了两个操作Operation1和Operation2,因其他的方法使用继承自Service的方法,执行后没有LOG信息出现。

表4-2-13 简化后的intentServiceTest类

package com.example.intentservice;

import android.app.IntentService;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class intentServiceTest extends IntentService {
    final String TAG="chen";
    public intentServiceTest() {
        //必须实现父类的构造方法
        super("intentServiceTest");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
      
        String action = intent.getExtras().getString("param");
            if (action.equals("oper1")) {
                Log.e(TAG, "Operation1");
            }else if (action.equals("oper2")) {
                Log.e(TAG, "Operation2 " );
            }
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

只重写onHandleIntent()方法后LOG信息,图4-2-13展示出的信息中可以看到,两个操作Operation1和Operation2均得到了执行。

16