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

时间:2019-04-12 12:50:29

标签: android bluetooth-lowenergy android-runonuithread

在我的片段中,我有一个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.

这里会发生什么?

1 个答案:

答案 0 :(得分:1)

替换为

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...");
               }
           });
       }
   });