Activity.runOnUiThread(Runnable action) 只更新视图一次

Activity.runOnUiThread(Runnable action) only updates view once

在我的片段中,我有一个 AlertDialog 和一个蓝牙连接管理器。我想用蓝牙连接过程的新状态更新 AlertDialog,所以我使用了 runOnUiThread(...) 方法:

getActivity().runOnUiThread(new Runnable() {
    @Override
    void run() {
        interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
            @Override
            public void OnConnectionStopped() {
                alertDialog.setMessage("Disconnected.");
            }

            @Override
            public void OnConnectionStopping() {
                alertDialog.setMessage("Stopping connection...");
            }

            @Override
            public void OnConnectionStarting() {
                alertDialog.setMessage("Connecting to device...");
            }

            @Override
            public void OnConnectionStarted() {
                alertDialog.setMessage("Streaming data...");
            }
        });
    }
});

我第一次更新 AlertDialog 消息(OnConnectionStarting 事件)一切正常,但第二次我收到 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

这里可能发生了什么?

替换为

interactor = new BluetoothInteractor(getActivity(), new OnBluetoothStatusChangedListener() {
       @Override
       public void OnConnectionStopped() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Disconnected.");
               }
           });
       }
       @Override
       public void OnConnectionStopping() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Stopping connection...");
               }
           });
       }
       @Override
       public void OnConnectionStarting() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Connecting to device...");
               }
           });
       }
       @Override
       public void OnConnectionStarted() {
           getActivity().runOnUiThread(new Runnable() {
               @Override
               void run() {
                   alertDialog.setMessage("Streaming data...");
               }
           });
       }
   });