我有以下代码。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秒)
谢谢墨菲先生。它显示了我在什么程度上没有得到Java和Android的概念:)我认为,当我们在新的Handler()中有“new Thread()”时,postDelayed会创建新的线程。 – Hesam
@Hesam:好的,你正在创建一个'Thread'对象的实例。但是,除非有人在你的'Thread'对象上调用'start()',否则不会创建实际的OS *线程*。由于'postDelayed()'只是将对象视为'Runnable','postDelayed()'不会调用'start()',只是'run()'。因此,你的'run()'代码将在主应用程序线程上执行,而不是后台线程。 – CommonsWare
这么多有用的信息在一个单一的答案。 –