java.lang.RuntimeException:无法在线程内创建处理程序

时间:2012-02-17 10:18:44

标签: android bluetooth handler

我收到错误...无法在未调用Looper.prepare()的线程内创建处理程序

其实我的情况是这样的: 我正在尝试使用Android开发人员提供的“BluetoothChat”示例代码。我的任务是设置一个应用程序运行并在连接远程设备后自动发送消息...我想你们都知道我想说的是什么...... 我有String消息,我希望应用程序每秒发送一次远程设备:

String helloString[] = {"hello person"," hi there", "hola hola", "yau yau..."};

在这里,我尝试更改代码的某些部分,我认为应用程序将执行我想要的失败... :(

private void setupChat() 
    {
    Log.d(TAG, "setupChat()");

    Thread output = new Thread()
    {
        public void run()
    {
            while (true)
            {
                for(int i = 0; i < 4; i++)
                {

                    //Sending helloStrings for the device
                    message = helloString[i];       
                    sendMessage(message);

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                    }
                }
            }
    }
    };
    output.start();

    // Initialize the BluetoothChatService to perform bluetooth connections
    mChatService = new BluetoothChatService(this, mHandler);


}

/**
     * Sends a message.
     * @param message  A string of text to send.
     */   
    private void sendMessage(String message) 
    {
        // TODO Auto-generated method stub
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) 
        {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();           
            return;
        }

        byte[] send = message.getBytes();
        mChatService.write(send);

    }

1 个答案:

答案 0 :(得分:0)

您还需要在 run()方法上声明@Override。

请参阅此问题的已接受答案How to run a Runnable thread in Android?