我有以下代码。
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);
}
}
我在分析这段代码时遇到了问题。据我所知,handler是在主线程中运行的。但它有一个在其他线程中运行的线程。
MainMenu.class会在主线程或第二个线程中运行吗?
如果主线程停止5秒钟,就会引发ANR。为什么当我用延迟(_splashTime)
停止它时,即使我将其增加到5秒以上,ANR也不会显示?
Thread
对象的实例。但是,除非有人在你的Thread
对象上调用了start()
,否则不会创建实际的操作系统 线程 。由于postDelayed()
只将该对象视为Runnable
,因此postDelayed()
不会调用start()
,而只会调用run()
。因此,你的run()
代码将在主应用程序线程上执行,而不是在后台线程上执行。 - CommonsWarerun()
在被调用时是在不同的线程上运行还是在主应用程序线程上运行,这取决于是否使用new Thread() { }
创建了一个新的线程。 - Malwinder SinghpostDelayed()
的Runnable
上的run()
,它将在主应用程序线程上运行。 - CommonsWare