java – AndroidAnnotations的@UiThread是如何实现的?

AndroidAnnotations提供了一个允许在UI线程上运行方法的注释,无论从哪个线程调用它,例如,

void myMethod() {
    doInUiThread("hello", 42);
}

@UiThread
void doInUiThread(String aParam, long anotherParam) {
    [...]
}

AndroidAnnotations Wiki @UiThread开始.

这个注释是如何实现的?

我知道注释生成器可以生成其他类,例如继承Runable.但是注释如何称之为自定义代码?注释是否可以修改方法本身或调用它的位置?

最佳答案 我不确定Android Annotations项目,但正常的Android支持注释不会自动切换到UI线程来调用这些方法 – 它们只是对编码器(和任何代码验证器)的指示,该方法应该只能从UI线程调用.

换句话说,即使使用@UiThread注释,此代码仍会抛出CalledFromWrongThreadException:

import android.support.annotation.UiThread;
...

public class XYZ extends Activity {

    public void onCreate(Bundle b) {
         super.onCreate();
         setContentView(R.layout.xyz);

         new Thread(new Runnable() {
               @Override
               public void run() {
                  XYZ.this.updateUI();
               }
         }).start();
    }

    @UiThread
    void updateUI() {
        ((TextView) findViewById(R.id.texty)).setText("Whoops");
    }
}

从您在问题中引用的Support Annotations链接中解释:

If you attempt to call [a @UiThread method] from a method which overrides
doInBackground, or if you call into any View method, the tools will
now flag this as an error

这些工具会将其标记为错误,但App仍然可以构建并运行(尽管它可能会像上面那样崩溃).

点赞