2015-12-16 37 views
2

我創建了兩個Activity「SplashActivity和AuthenticationActivity」,當我啓動應用程序時,它加載SplashScreen 5秒並移至AuthenticationActivity。 現在我的問題是當我運行應用程序加載splashScreen,但在5秒內,當我點擊返回按鈕SplashActivity退出並立即AuthenticationActivity出現在前臺。 如何編碼當我點擊返回按鈕我的應用程序應該退出。下面附按下按鈕SplashScreen退出並打開身份驗證活動

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

不使用線程使用處理器 – Pavya

+0

刪除super.onBackPressed(); 從onbackpress方法它將禁用回來按 – koutuk

+0

可能重複[從歷史堆棧中刪除活動](http://stackoverflow.com/questions/1898886/removing-an-activity-from-the-history-stack) – Vlad274

回答

5
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; 
    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); 
} 
+0

任何人都可以幫助我如何使用處理程序和運行在我的splashScreen – Rahul

+0

編碼答案與處理程序和標記爲接受。 –