android.view.ViewRoot$CalledFromWrongThreadException 异常的解决方案

https://blog.csdn.net/vincent_czz/article/details/7070354

https://stackoverflow.com/questions/21014152/android-view-viewrootimplcalledfromwrongthreadexception-only-the-original-thr

也就是说必须在程序的主线程(也就是ui线程)中进行更新界面显示的工作。可以采用下面的方法之一来解决:

解决方案1:在activity.oncreate(bundle savedinstancestate)中创建一个handler类的实例, 在这个handler实例的handlemessage回调函数中调用更新界面显示的函数。例如:

public class ExampleActivity extends Activity {
    Handler h = null;

    @override
    public void onCreate(Bundle savedinstancestate) {
        h = new Handler() {
            @override
            public void handleMessage(Message msg) {
            // call update gui method.
            }
        };
    }
}

在其它的函数中,利用 send族或post族函数向这个h发送或邮寄消息即可。

 

解决方案2:利用activity.runOnUiThread(runnable)

  把更新ui的代码创建在runnable中,然后在需要更新ui时,把这个runnable对象传给activity.runOnUiThread(runnable)。 这样runnable对像就能在ui程序中被调用。

posted @ 2019-05-21 09:32  petercao  阅读(9391)  评论(0编辑  收藏  举报