从另一个线程调用更新Android UI的方法是否有效? [英] Is it a bug that calling methods that update Android UI from another thread works?

查看:36
本文介绍了从另一个线程调用更新Android UI的方法是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会给你两段代码.一个代码更新子线程的 UI.是的,你没听错!

I will give you two pieces of code. One code updates the UI for the child thread. Yes, you heard me correctly!

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".NbPlus">
    <TextView
        android:id="@+id/tv_test"
        android:text="TEXT"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:onClick="updateText"
        android:text="updateText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>

Java 代码

public class NbPlus extends AppCompatActivity {
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_question);
        textView = findViewById(R.id.tv_test);
    }

    public void updateText(View view) {
        System.out.println("NB PLUS");
        new Thread(() -> textView.setText("Click Me!!!")).start();
    }
}

现在可以运行这段代码了,不可思议,它运行正常.如果你能解释原因,请告诉我.

Now you can run this code, which is incredible, it works correctly。 If you can explain why, please let me know。

推荐答案

这不是一个错误,但也不能保证它有效.Android UI 工具包 API 契约是对 UI 的更新必须在 UI 线程(几乎总是与主线程相同)上完成.如果您通过从另一个线程进行更新而违反此规则会发生什么,正如您对 setText 的调用所做的那样,未定义.它可能有效,也可能没有效果,可能会立即崩溃,或者可能会巧妙地破坏事物和/或稍后崩溃.

This is not a bug, but it's not guaranteed to work, either. The Android UI toolkit API contract is that updates to the UI must be done on the UI thread (which is almost always the same as the main thread). What happens if you violate this rule by making an update from another thread, as you've done with your call to setText, is not defined. It may work, it may have no effect, it may crash immediately, or it may subtly break things and/or crash later.

许多通常被错误线程错误调用的方法会显式检查它们所在的线程,如果不是 UI 线程则会崩溃.这是一项旨在帮助开发人员更轻松地发现错误的功能,而不是任何 UI 修改方法调用的必需行为.

Many methods that are commonly mistakenly called from the wrong thread explicitly check what thread they're on, and crash if it's not the UI thread. This is a feature intended to help developers more easily catch their mistakes, rather than a required behavior of any UI-modifying method call.

这篇关于从另一个线程调用更新Android UI的方法是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆