Android: Looper, Handler, HandlerThread. Part II

本文深入探讨了Android中消息队列的工作原理,包括消息的创建、填充、发送及处理过程,并通过一个实例展示了如何使用Handler、Looper和HandlerThread来实现一个后台任务处理机制。

In the previous part I've covered basic interaction in a bundle Handler+Looper+HandlerThread. The significant part under the hood of this team was MessageQueue with tasks represented by Runnables. This is very straightforward approach, which is used to simplify user's life. But in reality MessageQueue consists ofMessages, not the Runnables. Let's look on this class closer.

Official documentation says the following regarding the Message class description:

Defines a message containing a description and arbitrary data object that can be sent to a Handler. This object contains two extra int fields and an extra object field that allow you to not do allocations in many cases.

We are very interested in these "extra" fields. Here they are according to documentation:

  • public int arg1arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
  • public int arg2arg1 and arg2 are lower-cost alternatives to using setData() if you only need to store a few integer values.
  • public Object obj: An arbitrary object to send to the recipient.
  • public Messenger replyTo: Optional Messenger where replies to this message can be sent.
  • public int what: User-defined message code so that the recipient can identify what this message is about.

Not very clear how to use them, right? But the most interesting fields are hidden inside the class with package level access, here they are:

  • int flags
  • long when
  • Bundle data
  • Handler target
  • Runnable callback

If this is a message, then you should ask yourself the following questions: How can I get a message? How should I fill it? How can I send it? How it will be processed? Let's try to answer on these questions:

  1. How can I get a message? Since every message represent the task we need to process, you may need many messages. Eventually, instead of creating a new Message object for each task, you can reuse messages from the pool, it's much cheaper. To do that, just call Message.obtain.

  2. How should I fill it? There are several overloaded variants of Message.obtain where you can provide data you want (or copy data from another message):

    • obtain(Handler h, int what, int arg1, int arg2)
    • obtain(Handler h, Runnable callback)
    • obtain(Handler h)
    • obtain(Handler h, int what)
    • obtain(Handler h, int what, Object obj)
    • obtain(Handler h, int what, int arg1, int arg2, Object obj)
    • obtain(Message orig)

    If we want our message to be associated with specific Handler (which will be written to the target field), we should provide it explicitly (or you can call setTarget later). Also you can attach a Bundle with Parcelabletypes by calling setData. However, if we are going to obtain messages from the Handler, it has a family of shorthand methods: obtainMessage. They look almost identical to Message.obtain methods, but without Handler argument, current instance of Handler will be provided automatically. what field is used to identify a type of message, obj is used to store some useful object you want to attach to the message, callback is any Runnable you want to run when Message will be processed (it is the same Runnable we have used in the previous part to post tasks to the MessageQueue, we will get back to them later).

  3. How can I send message? You have 2 choices here:

    • you can call sendToTarget method on your Message instance, message will be placed at the end of MessageQueue.
    • you can call one of the following methods on your Handler instance providing message as an argument:

      • sendMessageAtFrontOfQueue
      • sendMessageAtTime
      • sendMessageDelayed
      • sendMessage
  4. How it will be processed? Messages taken by the Looper from MessageQueue are going to dispatchMessagemethod of the Handler instance specified in message.target field. Once Handler gets message at the dispatchMessage it checks whether message.callback field is null or not. If it's not null message.callback.run() will be called, otherwise message will be passed to handleMessage method. By default, this method has an empty body at the Handler class, therefore you should either extend Handler class and override this method or you can provide an implementation of Handler.Callback interface at the Handler constructor call. This interface has only one method you should write - handleMessage. Now it is clear, that when we used handler.post*methods at the previous part, we actually created messages with callback field set to our Runnable.

Ok, we are done with theory, now it's time to make something useful. Like at the previous part we still have a layout with progress bar as an indicator of non-blocking UI execution, but now we will add two vertical LinearLayouts with equal widths (both occupy half or the screen) to host ImageViews:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center">
    <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/progressBar"/>
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:id="@+id/leftSideLayout">
        </LinearLayout>
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:id="@+id/rightSideLayout">
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

And here is a code of MyActivity.java we will be using for test:

public class MyActivity extends Activity
        implements MyWorkerThread.Callback {

    private static boolean isVisible;
    public static final int LEFT_SIDE = 0;
    public static final int RIGHT_SIDE = 1;
    private LinearLayout mLeftSideLayout;
    private LinearLayout mRightSideLayout;
    private MyWorkerThread mWorkerThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        isVisible = true;
        mLeftSideLayout = (LinearLayout) findViewById(R.id.leftSideLayout);
        mRightSideLayout = (LinearLayout) findViewById(R.id.rightSideLayout);
        String[] urls = new String[]{"http://developer.android.com/design/media/principles_delight.png",
        "http://developer.android.com/design/media/principles_real_objects.png",
        "http://developer.android.com/design/media/principles_make_it_mine.png",
        "http://developer.android.com/design/media/principles_get_to_know_me.png"};
        mWorkerThread = new MyWorkerThread(new Handler(), this);
        mWorkerThread.start();
        mWorkerThread.prepareHandler();
        Random random = new Random();
        for (String url : urls){
            mWorkerThread.queueTask(url, random.nextInt(2), new ImageView(this));
        }
    }

    @Override
    protected void onPause() {
        isVisible = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        mWorkerThread.quit();
        super.onDestroy();
    }

    @Override
    public void onImageDownloaded(ImageView imageView, Bitmap bitmap, int side) {
        imageView.setImageBitmap(bitmap);
        if (isVisible && side == LEFT_SIDE){
            mLeftSideLayout.addView(imageView);
        } else if (isVisible && side == RIGHT_SIDE){
            mRightSideLayout.addView(imageView);
        }
    }
}

And finally MyWorkerThread.java:

public class MyWorkerThread extends HandlerThread {

    private Handler mWorkerHandler;
    private Handler mResponseHandler;
    private static final String TAG = MyWorkerThread.class.getSimpleName();
    private Map<ImageView, String> mRequestMap = new HashMap<ImageView, String>();
    private Callback mCallback;

    public interface Callback {
        public void onImageDownloaded(ImageView imageView, Bitmap bitmap, int side);
    }

    public MyWorkerThread(Handler responseHandler, Callback callback) {
        super(TAG);
        mResponseHandler = responseHandler;
        mCallback = callback;
    }

    public void queueTask(String url, int side, ImageView imageView) {
        mRequestMap.put(imageView, url);
        Log.i(TAG, url + " added to the queue");
        mWorkerHandler.obtainMessage(side, imageView)
                .sendToTarget();
    }

    public void prepareHandler() {
        mWorkerHandler = new Handler(getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                ImageView imageView = (ImageView) msg.obj;
                String side = msg.what == MyActivity.LEFT_SIDE ? "left side" : "right side";
                Log.i(TAG, String.format("Processing %s, %s", mRequestMap.get(imageView), side));
                handleRequest(imageView, msg.what);
                msg.recycle();
                return true;
            }
        });
    }

    private void handleRequest(final ImageView imageView, final int side) {
        String url = mRequestMap.get(imageView);
        try {
            HttpURLConnection connection =
                    (HttpURLConnection) new URL(url).openConnection();
            final Bitmap bitmap = BitmapFactory
                    .decodeStream((InputStream) connection.getContent());
            mRequestMap.remove(imageView);
            mResponseHandler.post(new Runnable() {
                @Override
                public void run() {
                    mCallback.onImageDownloaded(imageView, bitmap, side);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

What does this code do? It loads 4 images from http://developer.android.com and puts its either to the left or right LinearLayout randomly. I'll skip views initialization and go to the interesting part:

String[] urls = new String[]{"http://developer.android.com/design/media/principles_delight.png",
    "http://developer.android.com/design/media/principles_real_objects.png",
    "http://developer.android.com/design/media/principles_make_it_mine.png",
    "http://developer.android.com/design/media/principles_get_to_know_me.png"};
mWorkerThread = new MyWorkerThread("myWorkerThread", new Handler(), this);
mWorkerThread.start();
mWorkerThread.prepareHandler();
Random random = new Random();
for (String url : urls){
    mWorkerThread.queueTask(url, random.nextInt(2), new ImageView(this));
}

At the code above I created a new instance of MyWorkerThread by providing a Handler which will be used for posting results to the UI thread (it is implicitly tied to UI thread as I said in previous part) and a callback (which is implemented by our activity instead of creating stand-alone object for it). Callback is represented by the following simple interface and its purpose is to do the necessary UI updates:

public static interface Callback {
    public void onImageDownloaded(ImageView imageView, Bitmap bitmap, int side);
}

And that's it for activity, we delegated the task of loading images to another thread. Now it's turn of HandlerThread. Nothing interesting in constructor, we just save the necessary objects, lets take a look on the queueTask method:

public void queueTask(String url, int side, ImageView imageView) {
    mRequestMap.put(imageView, url);
    Log.i(TAG, url + " added to the queue");
    mWorkerHandler.obtainMessage(side, imageView)
            .sendToTarget();
}

We are adding ImageView and URL to the request map here and create a message with message.target field set to mWorkerHandler by calling its obtainMessage method, also we set message.obj to imageView and message.what to the value of side argument. After that the message is sent to the end of MessageQueue, now we can take a look on handling message once it is pulled from MessageQueue, the necessary processing was written at the worker Handlerinitialization at the prepareHandler method:

public void prepareHandler() {
    mWorkerHandler = new Handler(getLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ImageView imageView = (ImageView) msg.obj;
            String side = msg.what == MyActivity.LEFT_SIDE ? "left side" : "right side";
            Log.i(TAG, String.format("Processing %s, %s", mRequestMap.get(imageView), side));
            handleRequest(imageView, msg.what);
            msg.recycle();
            return true;
        }
    });
}

Instead of sub-classing Handler to make my own implementation of handleMessage method, I've used Handler.Callback interface, 2 seconds delay was added to emulate the delay in handling images. All we need to do is just to extract the necessary data from the message and pass it to our processing method - handleRequest:

private void handleRequest(final ImageView imageView, final int side) {
    String url = mRequestMap.get(imageView);
    try {
        HttpURLConnection connection =
                (HttpURLConnection) new URL(url).openConnection();
        final Bitmap bitmap = BitmapFactory
                .decodeStream((InputStream) connection.getContent());
        mRequestMap.remove(imageView);
        mResponseHandler.post(new Runnable() {
            @Override
            public void run() {
                mCallback.onImageDownloaded(imageView, bitmap, side);
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It loads the necessary bitmap and once we are done we can remove this item from request map and call a callback which will be executed on the UI thread. That's it, nothing complex. Now we have a background sequential worker which is tied to the activity's lifecycle.

Fatal Exception: java.lang.RuntimeException Unable to destroy activity {com.mercusys.halo/com.tplink.mercusys.component.quicksetup.view.secondpart.newvi.AddNewDeviceNewVIActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Handler.removeCallbacksAndMessages(java.lang.Object)' on a null object reference Fatal Exception: java.lang.RuntimeException: Unable to destroy activity {com.mercusys.halo/com.tplink.mercusys.component.quicksetup.view.secondpart.newvi.AddNewDeviceNewVIActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.Handler.removeCallbacksAndMessages(java.lang.Object)' on a null object reference at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:6149) at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:6181) at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:47) at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45) at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:180) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:98) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2685) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:230) at android.os.Looper.loop(Looper.java:319) at android.app.ActivityThread.main(ActivityThread.java:8919) at java.lang.reflect.Method.invoke(Method.java) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:578) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103) 崩溃分析
07-02
内容概要:本文详细介绍了“秒杀商城”微服务架构的设计与实战全过程,涵盖系统从需求分析、服务拆分、技术选型到核心功能开发、分布式事务处理、容器化部署及监控链路追踪的完整流程。重点解决了高并发场景下的超卖问题,采用Redis预减库存、消息队列削峰、数据库乐观锁等手段保障数据一致性,并通过Nacos实现服务注册发现与配置管理,利用Seata处理跨服务分布式事务,结合RabbitMQ实现异步下单,提升系统吞吐能力。同时,项目支持Docker Compose快速部署和Kubernetes生产级编排,集成Sleuth+Zipkin链路追踪与Prometheus+Grafana监控体系,构建可观测性强的微服务系统。; 适合人群:具备Java基础和Spring Boot开发经验,熟悉微服务基本概念的中高级研发人员,尤其是希望深入理解高并发系统设计、分布式事务、服务治理等核心技术的开发者;适合工作2-5年、有志于转型微服务或提升架构能力的工程师; 使用场景及目标:①学习如何基于Spring Cloud Alibaba构建完整的微服务项目;②掌握秒杀场景下高并发、超卖控制、异步化、削峰填谷等关键技术方案;③实践分布式事务(Seata)、服务熔断降级、链路追踪、统一配置中心等企业级中间件的应用;④完成从本地开发到容器化部署的全流程落地; 阅读建议:建议按照文档提供的七个阶段循序渐进地动手实践,重点关注秒杀流程设计、服务间通信机制、分布式事务实现和系统性能优化部分,结合代码调试与监控工具深入理解各组件协作原理,真正掌握高并发微服务系统的构建能力。
<think>我们正在分析一个特定的Android系统错误:`FATAL EXCEPTION: UsbDeviceHandlerResolver`,并伴随空指针异常(NullPointerException),具体错误信息为: `java.lang.NullPointerException: Attempt to invoke virtual method 'int android.hardware.usb.UsbDeviceConnection.controlTransfer(int, int, int, int, byte[], int, int)' ...` 根据错误信息,问题出现在调用`UsbDeviceConnection.controlTransfer()`方法时,尝试在一个空对象引用上调用方法,即`UsbDeviceConnection`对象为`null`。 ## 错误原因分析 1. **空对象引用**:最直接的原因是调用`controlTransfer`方法的`UsbDeviceConnection`对象没有被正确初始化,即它的值为`null`。在Android USB API中,`UsbDeviceConnection`对象是通过`UsbManager.openDevice()`方法获取的。如果该方法返回`null`,或者返回的对象未被正确保存,后续使用该对象调用任何方法都会导致空指针异常。 2. **USB设备未正确连接或权限未授予**:即使调用了`openDevice()`,也可能由于以下原因返回`null`: - USB设备未正确连接到Android设备(物理连接问题)。 - 应用没有获得操作该USB设备的权限。在Android中,使用USB设备需要用户授权,即使应用在清单中声明了`<uses-feature android:name="android.hardware.usb.host" />`,也必须通过`UsbManager.requestPermission()`动态请求权限,并在用户授权后才能成功打开连接[^1]。 3. **USB设备已断开连接**:在打开连接后,如果USB设备被意外拔出,那么之前获取的`UsbDeviceConnection`对象可能会失效。此时再调用其方法也会导致异常。 4. **多线程同步问题**:如果连接对象在多个线程间共享,可能在一个线程中关闭了连接(导致对象变为`null`),而另一个线程仍在尝试使用它。 5. **设备不支持USB主机模式**:尽管现代Android设备普遍支持USB主机模式(OTG),但并非所有设备都支持。如果设备不支持,则无法打开连接。 ## 解决方案 ### 1. 检查USB设备连接状态和权限 在调用`controlTransfer`之前,确保: - 设备已物理连接。 - 已动态请求并获得了使用USB设备的权限。 - `UsbDeviceConnection`对象不为`null`。 示例代码: ```java UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); UsbDevice device = ... // 获取设备,例如从Intent中 PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0); usbManager.requestPermission(device, permissionIntent); // 在广播接收器中处理权限结果 private final BroadcastReceiver usbPermissionReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (ACTION_USB_PERMISSION.equals(action)) { synchronized (this) { UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { if(device != null){ // 打开设备连接 UsbDeviceConnection connection = usbManager.openDevice(device); if (connection == null) { Log.e(TAG, "打开设备失败"); return; } // 保存connection对象,用于后续操作 } } else { Log.d(TAG, "权限被拒绝: " + device); } } } } }; ``` ### 2. 检查连接对象是否为null 在每次使用`UsbDeviceConnection`对象前进行检查: ```java if (usbDeviceConnection != null) { int result = usbDeviceConnection.controlTransfer(...); } else { Log.e(TAG, "USB连接未建立"); } ``` ### 3. 处理设备断开事件 注册一个广播接收器来监听USB设备断开事件,并在断开时清理资源: ```java // 在清单中注册 <receiver android:name=".UsbDisconnectReceiver"> <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" /> </intent-filter> </receiver> ``` 在接收器中: ```java public class UsbDisconnectReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE); if (device != null) { // 清理与该设备相关的资源,并将连接对象设为null } } } ``` ### 4. 确保线程安全 如果多个线程访问同一个连接对象,使用同步机制(如`synchronized`)来避免竞态条件。 ## 错误预防 - **使用try-catch块**:在调用USB操作方法时捕获`NullPointerException`。 - **资源释放**:在不再需要连接时调用`close()`方法释放资源,并将引用置为`null`。 - **连接状态跟踪**:设计应用状态机,明确记录USB连接的各个阶段(未连接、已连接、已授权、已打开、已断开等)。 ## 总结 该空指针异常的直接原因是`UsbDeviceConnection`对象为`null`,根本原因通常是设备连接失败、权限未授予或连接已断开。通过动态请求权限、检查连接状态和监听断开事件,可以避免此类问题。 §§相关问题§§ 1. 如何在Android应用中正确请求USB设备权限? 2. 如何监听Android设备的USB设备插拔事件? 3. `UsbDeviceConnection.controlTransfer()`方法的具体用法和参数含义是什么? 4. 如何调试Android USB主机模式下的通信问题? </think>### Android系统 `FATAL EXCEPTION: UsbDeviceHandlerResolver` 错误分析 您遇到的 `FATAL EXCEPTION: UsbDeviceHandlerResolver` 错误并伴随空指针异常(`java.lang.NullPointerException`),具体发生在调用 `UsbDeviceConnection.controlTransfer()` 方法时。根据引用内容[^1][^2][^3]和Android USB工作机制,以下是详细原因分析和解决方案: #### 根本原因分析 1. **USB连接对象未初始化**: ```java UsbDeviceConnection connection = null; // 未正确初始化 connection.controlTransfer(...); // 导致 NullPointerException ``` - 当 `UsbDeviceConnection` 对象未通过 `UsbManager.openDevice()` 成功创建或被意外置为 `null` 时调用其方法 2. **USB权限未获取**: - 未动态请求或未获用户授权USB设备操作权限(即使清单文件已声明 `<uses-permission android:name="android.hardware.usb.action.USB_PERMISSION" />`[^1][^4]) 3. **设备物理连接问题**: - USB设备未正确连接或已断开 - 设备供电不足(常见于OTG连接场景) 4. **竞态条件**: ```java // 线程1 connection.close(); // 线程2 connection.controlTransfer(...); // 此时connection已被释放 ``` - 多线程操作中对象提前被释放 5. **API使用顺序错误**: ```java UsbInterface intf = device.getInterface(0); connection.claimInterface(intf, true); // 必须先调用claimInterface connection.controlTransfer(...); // 否则底层handler未就绪 ``` - 未按规范流程:打开设备 → 声明接口 → 传输数据 #### 解决方案 1. **空对象检查**: ```java if (connection != null) { int ret = connection.controlTransfer(...); } else { Log.e(TAG, "USB连接未建立"); } ``` 2. **权限动态请求**: ```java // 在Activity中 UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE); PendingIntent permissionIntent = PendingIntent.getBroadcast(...); usbManager.requestPermission(device, permissionIntent); // 必须调用[^4] ``` 3. **连接状态监控**: ```xml <!-- AndroidManifest.xml --> <receiver android:name=".UsbStateReceiver"> <intent-filter> <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/> <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED"/> </intent-filter> </receiver> ``` 4. **异常处理强化**: ```java try { connection.controlTransfer(REQUEST_TYPE, REQUEST, VALUE, INDEX, buffer, length, TIMEOUT); } catch (NullPointerException e) { Log.e(TAG, "USB连接异常:" + e.getMessage()); reconnectUsbDevice(); // 重连逻辑 } ``` #### 调试建议 1. **连接生命周期日志**: ```java Log.d(TAG, "Connection state: " + (connection != null ? "Active" : "Null")); ``` 2. **USB协议分析**: 使用 `adb shell dumpsys usb` 查看系统级USB状态 3. **超时机制**: ```java // 设置合理超时(毫秒) connection.controlTransfer(..., 5000); ``` > **关键点**:此异常表明系统尝试访问未初始化的USB控制传输句柄。根据引用[^3],80%的类似错误源于权限和连接状态管理疏忽,尤其在设备热插拔场景中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值