2015-06-07 100 views
1

一般來說,當點擊後退按鈕時,我打電話finish(),和我帶回以前activity(這是我MenuActivity):如何檢查現有活動時,後退按鈕按下

@Override 
public void onBackPressed() { 

    finish(); 

} 

然而,有時候沒有其他的activities在後退按鈕被點擊並且應用程序退出時運行。有沒有一種方法,我可以檢查是否有activity存在,或者在後臺運行/在狀態等等

我還想寫是這樣的:如果你知道

@Override 
public void onBackPressed() { 

    if(isActivitiesInStack) //if there are still activities in stack 

     finish(); //simply call finish and be taken back to next activity 

    else { // else, there are no acitivites in the stack 

     Intent intent = new Intent(ThisActivity.this, MenuActivity.class); // then create an intent and send me to the menu acitivy 
     startActivity(intent); 
     finish()   
    } 
} 
+0

檢查[此鏈接(不建議使用HTTP://計算器.com/a/6242122/2715073)可能會對您有所幫助 – Pankaj

回答

0

這您想要進入的活動onBackPressed()您可以使用FLAG_ACTIVITY_CLEAR_TOP開始活動。如果實例存在,它將切換到MenuActivity的實例,但它也會刪除當前活動實例和實例之間的所有活動實例。在另一種情況下,它只會啓動一個新實例。

Intent intent = new Intent(context, MenuActivity.class); 
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
startActivity(intent); 
0

我想,這可能會對你有所幫助

public boolean isRunning(Context ctx) { 
    ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); 
    List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE); 

    for (RunningTaskInfo task : tasks) { 
     if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName())) 
      return true;         
    } 

    return false; 
} 

總之這種方法已經在Android API 21(棒棒堂)

相關問題