文章标题

来源:互联网 发布:天然气期货交易软件 编辑:程序博客网 时间:2024/06/07 19:23

AndroidStudio: Method must be called from the Ui Thread

前言,

* 在学习中,可能会有童鞋发现一个有趣的现象,AndroidStudio中在一些方法中调用View的方法,会报出警告    Method xx must be called from the UI Thread,currently inferred thread is work thread    大致意思是xx()方法必须在UI线程中调用,但是当前线程是子线程* 在eclipse中却没有这样的情况,那么是什么原因呢? 请听下文

Android Studio中的注解

Studio是一款强大的开发工具,它的编译机制也是和eclipse不尽相同的,同时它也新增了很多eclipse没有的内容,比如要介绍的注解;
Studio中有着很多的注解,常见的@Nullable,@NonNull,以及本文要介绍的@UiThread,@WorkThread,…

@UiThread:
* 源码:
/**
* Denotes that the annotated method or constructor should only be called on the UI thread.
* If the annotated element is a class, then all methods in the class should be called
* on the UI thread.
*


被标注的如果是方法或构造方法,只应该被UI线程中调用
如果被标注的元素是一个类,然后这个类中的所有方法应该在UI线程中调用 (不包含构造方法)
*/
@Retention(CLASS) // 编译时注解
@Target({METHOD,CONSTRUCTOR,TYPE}) //作用域为方法,构造方法,类或接口
public @interface UiThread {
}
* 结论:
当某个方法被UiThread标注后,这个方法只能在UI线程去调用;换句话说,能调用这个方法的线程肯定是UI线程

WorkThread
* 源码:
/**
* Denotes that the annotated method should only be called on a worker thread.
* If the annotated element is a class, then all methods in the class should be called
* on a worker thread.
* 被标注的如果是方法,那么该方法应该在子线程中去调用
* 被标注的如果是一个类,那么该类的所有方法应该在子线程中去调用
*/
@Retention(CLASS)
@Target({METHOD,CONSTRUCTOR,TYPE})
public @interface WorkerThread {
}
* 结论
当某个方法被WorkThread标注后,这个方法只能在子线程去调用;换句话说,能调用这个方法的线程肯定是子线程

Demo
public class MainActivity extends AppCompatActivity {
private ClassB mClassB;
private ClassA mClassA;

        @Override        protected void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);            setContentView(R.layout.activity_main);            mClassB = new ClassB();            mClassA = new ClassA(){                public void methodA() {                     mClassB.methodB(); //编译时异常: Method methodB must be called from the UI Thread,currently inferred thread is work thread                }            };        }        public abstract class ClassA{            @WorkerThread   //methodA should called on a work thread            public abstract void methodA();         }        @UiThread           public class ClassB{            //methodB should called on a ui/main thread because of this type 'ClassB' annotated by UiThread            public void methodB(){            }        }    }

结论:

看了源码,发现原因了吧,报警告的原因就是因为我们在标注了WorkThread注解的方法中调用了标注UiThread的方法,studio在编译的时候发现了这个隐患,直接给我们提前报出来了;
至于为什么eclipse没有报,那是因为eclipse没有加注解;为什么eclipse没有加注解,是因为eclipse没有那种编译机制,加了也没用

0 0
原创粉丝点击