美文网首页
Android 子线程更新UI

Android 子线程更新UI

作者: jacobcyl | 来源:发表于2015-11-05 14:02 被阅读0次
    Can't create handler inside thread that has not called Looper.prepare()
    

    Activity 中创建了一个子线程用以请求HTTP,回调函数中想要更新UI,比如

    Toast.make(context, message).show()
    

    出现文章开头的错误,便知道是Looper的问题

    一般来说在工作线程中执行耗时任务,当任务完成时,会返回UI。这时有两种方法可以达到目的。
    一种是handler.sendMessage。发一个消息,再根据消息,执行相关任务代码。
    另一种是handler.post(r)。r是要执行的任务代码。意思就是说r的代码实际是在UI线程执行的。可以写更新UI的代码。(工作线程是不能更新UI的)。
    可参考Volley中的做法:

        if(Looper.myLooper() != Looper.getMainLooper()) {
            Handler mainThread = new Handler(Looper.getMainLooper());
            mainThread.post(new Runnable() {
            public void run() {
                Request.this.mEventLog.add(tag, requestTime);
                Request.this.mEventLog.finish(this.toString());
            }
        });
        return;}
    

    相关文章

      网友评论

          本文标题:Android 子线程更新UI

          本文链接:https://www.haomeiwen.com/subject/ymqchttx.html