【问题标题】:obtainMessage arguments meaning获取消息参数含义
【发布时间】:2013-07-14 18:55:34
【问题描述】:

我正在尝试理解这段代码:

        public void run() {
            byte[] buffer = new byte[1024];  // buffer store for the stream
            int bytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs
            while (true) {
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } catch (IOException e) {
                    break;
                }
            }
        }

唯一对我来说完全模糊的是obtainMessage(MESSAGE_READ, bytes, -1, buffer),它对应于下一个声明:

public final Message obtainMessage (int what, int arg1, int arg2, Object obj)

Added in API level 1
Same as obtainMessage(), except that it also sets the what, obj, arg1,and arg2 values on the returned Message.

Parameters
what    Value to assign to the returned Message.what field.
arg1    Value to assign to the returned Message.arg1 field.
arg2    Value to assign to the returned Message.arg2 field.
obj     Value to assign to the returned Message.obj field.

那么,请有人向我解释一下这些参数是什么以及它们的作用是什么?

P.S.:MESSAGE_READ 在该代码中未定义。

【问题讨论】:

    标签: android methods arguments message


    【解决方案1】:
    mHandler.obtainMessage():
    

    通过使用这种方法,我们允许 Android 处理消息对象池化,这有助于降低对象分配,尤其是在您频繁创建消息时,例如使用动画处理程序。

    what:用户定义的消息代码,以便收件人可以识别此消息的内容。

    obj 发送给接收者的任意对象。

    如果您只需要存储几个整数值,

    arg1 和 arg2 是使用 setData() 的低成本替代方案。

    【讨论】:

    • 如果我想存储更多整数怎么办
    【解决方案2】:

    它们都是由你定义的。什么是身份证。它通常是在拥有您发布到的处理程序的类中定义的枚举或常量。它应该定义消息的类型,假设有多个消息要发送。 arg1、arg2 和 obj 都是随消息一起发送的值,以防您需要向其传递数据。它们可以保持你想要的任何值,或者根本没有。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2022-06-22
      • 2013-10-24
      • 2016-01-29
      相关资源
      最近更新 更多