我创建了两个Activity" 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();
}}
答案 0 :(得分:6)
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);
}