向正在侦听网络数据的线程发送消息

时间:2013-04-19 12:20:26

标签: android service irc

我有一个Android应用程序,其中包含以下关键组件

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

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

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

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分: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,因此无需为活动编写looper。

默认情况下,线程没有looper,所以我们需要write 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>