微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Android,Handler是在主线程还是其他线程中运行?

我有以下代码.

public class SplashScreen extends Activity {
    private int _splashTime = 5000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        getwindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        new Handler().postDelayed(new Thread(){
           @Override
           public void run(){
             Intent mainMenu = new Intent(SplashScreen.this,MainMenu.class);
             SplashScreen.this.startActivity(mainMenu);
             SplashScreen.this.finish();
             overridePendingTransition(R.drawable.fadein,R.drawable.fadeout);
           }
        },_splashTime);
    }
}

我在分析这段代码时遇到了问题.至于知道处理程序在主线程中运行.但它有在其他线程中运行的线程.

MainMenu.class将在主线程或第二个线程中运行?
如果主线程停止5秒,ANR将被提升.为什么我延迟停止它(_splashTime)ANR不显示(即使我将它增加到超过5秒)

最佳答案

As far as kNow handler is running in main thread.

对象不在线程上运行,因为对象不运行.方法运行.

but it has thread which is running in other thread.

您尚未发布涉及任何“其他线程”的任何代码.上面代码清单中的所有内容都与流程的主应用程序线程相关联.

MainMenu.class will be run in main thread or second thread?

对象不在线程上运行,因为对象不运行.方法运行. MainMenu似乎是一个活动.在主应用程序线程上调用活动生命周期方法(例如,onCreate()).

Why when I am stopping it with delay (_splashTime) ANR doesn’t display (even if i increase it to more than 5 seconds)

你不是“延迟[主应用程序线程]”.您已安排在延迟_splashTime毫秒后在主应用程序线程上运行Runnable.但是,postDelayed()不是阻塞调用.它只是在事件队列上放置一个事件,该事件将不会在_splashTime毫秒内执行.

另外,请用Runnable替换Thread,因为postDelayed()不使用Thread.你的代码编译并运行,因为Thread实现了Runnable,但是你会认为使用Thread而不是Runnable意味着你的代码将在后台线程上运行,而不会.

原文地址:https://www.jb51.cc/android/430064.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐