0

我有一个具有以下关键组件的 Android 应用程序

管理连接线程的服务 连接到 IRC 并侦听来自绑定服务的连接 A ui 的消息的连接线程。

我在 UI 上有一个按钮,单击该按钮时我需要向 irc 服务器发送一条消息。我的想法是在连接线程上生成一个处理程序,在我的服务中获取它的句柄,然后将消息从 UI 发送到服务并从那里发送到线程。

当我在线程的类级别创建一个处理程序时,我得到一个 networkonuiexception。我将处理程序的实例化移动到 run() 方法,并被告知使用 Looper.prepare()。我觉得我处理错了,我正在寻找如何最好地管理这个问题的建议。

任何帮助,将不胜感激。

4

1 回答 1

1

当我开始学习 android 时,我编写了这个示例代码来处理线程中的消息,方法是looper

public class MainActivity extends Activity {

    Handler mHandler,childHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler(){
            public void handleMessage(Message msg) {
                TextView tv = (TextView) findViewById(R.id.displayMessage);
                tv.setText(msg.obj.toString());
            }
            };
        new LooperThread().start();
    }



    public void onSend(View v){
        Message msg = childHandler.obtainMessage();
        TextView tv = (TextView) findViewById(R.id.messageText);
        msg.obj = tv.getText().toString();


        childHandler.sendMessage(msg);
    }
    @Override
    protected void onStart() {
        super.onStart();
        LooperThread ttTest = new LooperThread();
        ttTest.start();
    }

    class LooperThread extends Thread {

        final int MESSAGE_SEND = 1;

        public void run() {
            Looper.prepare();
            childHandler = new Handler() {
                public void handleMessage(Message msg) {
                      Message childMsg =  mHandler.obtainMessage();
                      childMsg.obj = "child is sending "+(String)msg.obj;
                      mHandler.sendMessage(childMsg);
                }
            };
            Looper.loop();
        }
    }
}

它是一个示例代码,用于在按下按钮时向线程发送消息,然后线程通过向主活动添加一些字符串再次发送消息。您可以根据需要操作此代码。

Activity默认有looper,所以不需要为activity编写looper。

线程默认没有looper,所以我们需要写looper,它是一种存储消息的队列。

更新:

XML 代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

   <EditText
        android:id="@+id/messageText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Input message">
         <requestFocus />
    </EditText>
    <TextView
        android:id="@+id/displayMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >

    </TextView>

    <Button
        android:id="@+id/buttonSend"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onSend"
        android:text="Send" />

</LinearLayout>
于 2013-04-19T12:26:33.690 回答