文章标题
来源:互联网 发布:天然气期货交易软件 编辑:程序博客网 时间: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没有那种编译机制,加了也没用
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- Java程序员从笨鸟到菜鸟之(八十八)跟我学jquery(四)JQuery框架操作元素的属性与样式
- Java程序员从笨鸟到菜鸟之(八十九)跟我学jquery(五)jquery中的ajax详解
- 如何在CSDN-markdown编辑器写新文章上传图片的时候去掉水印
- Java程序员从笨鸟到菜鸟之(九十)跟我学jquery(六)jquery中事件详解
- 第一个汇编语言程序hello world
- 文章标题
- easyui 图片加载预览
- Java程序员从笨鸟到菜鸟之(九十一)跟我学jquery(七)jquery动画大体验
- C++的iostream标准库介绍
- R语言学习一(下载安装R-windows)
- 12161
- archlinux 默認瀏覽器(file manager)
- 阿里Weex框架快速体验与环境搭建
- Qt程序打包发布方法(使用官方提供的windeployqt工具)