您正在阻塞 UI 线程,这是一个很大的禁忌。onCreate
在您的方法返回之前,系统无法绘制屏幕。做你想做的事的一种常见方法是启动一个单独的线程等待,然后将 Runnable 发布到 UI 线程:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo);
final Handler handler = new Handler();
final Runnable doNextActivity = new Runnable() {
@Override
public void run() {
// Intent to jump to the next activity
Intent intent= new Intent(this, NextActivity.class);
startActivity(intent);
finish(); // so the splash activity goes away
}
};
new Thread() {
@Override
public void run() {
SystemClock.sleep(2000);
handler.post(doNextActivity);
}
}.start();
}
一种更简单的方法(正如 Athmos 在他的回答中建议的那样)是让处理程序为您进行倒计时:
Handler mHandler;
Runnable mNextActivityCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logo);
mHandler = new Handler();
mNextActivityCallback = new Runnable() {
@Override
public void run() {
// Intent to jump to the next activity
Intent intent= new Intent(this, NextActivity.class);
startActivity(intent);
finish(); // so the splash activity goes away
}
};
mHandler.postDelayed(mNextActivityCallback, 2000L);
}
这样做的好处是您可以取消继续进行下一个活动(例如,如果用户按下后退按钮,或者您在这 2 秒内检测到错误情况或其他情况):
@Override
protected void onPause() {
if (isFinishing()) {
mHandler.removeCallbacks(mNextActivityCallback);
}
}