【问题标题】:Calling a method form a different thread in Android从 Android 中的不同线程调用方法
【发布时间】:2015-01-13 00:55:46
【问题描述】:

如何使用在另一个线程(不是主线程)和不同类中定义的方法?直接示例是在 AndroidDev 上的蓝牙教程中有一个 ConnectedThread 类 在该类中有一个 write() 方法,用于将某些内容放在蓝牙的输出流上。我如何在主要活动中使用该方法,因为我想通过按下按钮发送信息?

private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) { //how do i use this method in the ui(main) activity?
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}

【问题讨论】:

  • 你的问题有点混乱-线程中没有定义函数。它们在类中定义。任何函数都可以在任何线程上调用,尽管这样做可能会导致系统其他地方出现问题,这是合法的 Java。

标签: java android multithreading bluetooth


【解决方案1】:

确保您尝试从另一个类访问的方法是公共方法。

【讨论】:

    【解决方案2】:

    在本例中,ma​​in Activity 调用一个 fragmentActivity 并在 layout main Activity 中显示该片段。您需要做的是在 layout fragmentActivity 中创建一个新按钮并在 onViewCreated 中实例化。在按钮初始化setupChat () 方法内的事件后,通过参数发送sendMessage ("yourMessage") 您的信息。片段活动中的所有内容。

    【讨论】:

      【解决方案3】:

      我建议使用 eventbus,例如 EventBus 或 Otto。如果要更改 UI,则需要注册事件,然后在主线程上运行代码,例如 Activity.runOnUIThread(){}

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-24
        • 1970-01-01
        • 2013-11-09
        • 2012-04-25
        • 1970-01-01
        • 1970-01-01
        • 2018-07-14
        • 1970-01-01
        相关资源
        最近更新 更多