2

我正在使用线程来执行一些 BT 任务。我正在尝试向 UI 线程发送消息,以便我可以根据我的 BT 线程进行 UI 工作。为此,我正在使用处理程序,但我不知道如何检索发送给处理程序的数据。

要发送数据,我使用:

handler.obtainMessage(intCode).sendToTarget();

其中 intCode 是一个 int。我的处理程序看起来像这样。

Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg){
        Bundle data = msg.getData();
        int code = data.getInt("what");
        Log.d(LOG_TAG, "Msg: "+code);
    }
}

但是代码的值永远不会是 0。在执行 .obtainMessage(int) 时如何获取发送的值?该值是否未存储在具有键“what”的 Bundle 中?

4

2 回答 2

3

您可以以这种格式设置数据

设置数据时

Message msg = new Message();
msg.obj = data which you want to set // for object data
Msg.arg1  = data which you want to set // for integer data

在获取数据时

String data = (String) msg.obj; // If object is of String
int integerData = msg.arg1;

msg.arg1 一次只传递一个数据你也可以在 msg.arg2 中传递数据,它们都是整数类型

于 2013-07-29T16:55:19.623 回答
0

您可以在参数 Message 下获取 Message 数据public boolean handleMessage(Message message)。例如,要在消息中获取 arg1,您可以:

mHandler = new Handler(this.getLooper(), new Handler.Callback() {

        @Override
        public boolean handleMessage(Message message) {
            switch (message.what){
                case MY_MESSAGE_1:
                    int argument1 = message.arg1;
                    return true;
                    ....
于 2018-05-21T19:23:56.843 回答