【问题标题】:java.lang.RuntimeException: Can't create handler inside threadjava.lang.RuntimeException:无法在线程内创建处理程序
【发布时间】:2012-02-18 02:36:54
【问题描述】:

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

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

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);

    }

【问题讨论】:

    标签: android bluetooth handler


    【解决方案1】:

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

    查看此问题的已接受答案How to run a Runnable thread in Android?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-27
      • 2019-06-04
      相关资源
      最近更新 更多