簡體   English   中英

按下后退按鈕時如何檢查現有活動

[英]How to check for existing activities when back button pressed

通常,當單擊后退按鈕時,我調用finish() ,然后將我帶回到上一個activity (這是我的MenuActivity):

@Override
public void onBackPressed() {

    finish();

}

但是,有時,當單擊后退按鈕並且應用程序退出時,沒有其他activities運行。 有沒有一種方法可以檢查activity存在或正在后台運行/處於onPause狀態等...

我想寫這樣的東西:

@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()          
    }
}

如果你知道你想要哪個活動中去onBackPressed()就可以開始與活動FLAG_ACTIVITY_CLEAR_TOP 如果存在實例,它將切換到MenuActivity實例,但是它也將刪除當前活動實例和MenuActivity實例之間的所有活動實例。 在其他情況下,它將僅啟動一個新實例。

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

我認為這可能對您有幫助

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(Lollipop)中棄用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM