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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Activity.runOnUiThread(Runnable action)仅更新视图一次相关的知识,希望对你有一定的参考价值。

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

以上是关于Activity.runOnUiThread(Runnable action)仅更新视图一次的主要内容,如果未能解决你的问题,请参考以下文章

Activity.runOnUiThread介绍-Android

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

Android 更新UI的两种方法——handler和runOnUiThread()

更新UI的四种方式

android开发--多线程

4.3 异步任务