我创建了一个两个活动“SplashActivity和AuthenticationActivity”,当我启动应用程序时,它会加载SplashScreen 5秒并移动到AuthenticationActivity。
现在我的问题是,当我运行应用程序时,它会加载SplashScreen,但在5秒内,当我单击后退按钮SplashActivity退出时,AuthenticationActivity立即出现在前台。
如何编码当我点击后退按钮我的应用应该退出。
我试过的代码附在下面
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Thread splashTimer = new Thread(){
public void run(){
try{
sleep(5000);
startActivity(new Intent(SplashActivity.this,AuthenticationActivity.class));
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
finish();
}
}
};
splashTimer.start();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
}}
最佳答案
Timer timer;
TimerTask timerTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
timer = new Timer();
timerTask = new TimerTask()
{
@Override
public void run()
{
//Start your activity here
}
};
timer.schedule(timerTask,2500);
}
@Override
public void onBackPressed() {
super.onBackPressed();
timer.cancel();
}
或者你可以使用handler
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
initialize();
}
private void initialize()
{
handler = new Handler();
runnable = new Runnable()
{
@Override
public void run()
{
//start your activity here
}
};
handler.postDelayed(runnable, 5000);
}
@Override
public void onBackPressed() {
super.onBackPressed();
handler.removeCallbacks(runnable);
}