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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/android/430064.html

猜你在找的Android相关文章