Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

java - Android Kotlin get the count of the BackStack in a second Activity

I have the following problem: I have an android application written with Kotlin.

The application has two Activities. From the fist one navigate to the second one like this:

val intent = Intent(firstActivity, SecondActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(intent)
firstActivity?.finish()

In the second Activity I overwrite the method onBackPressed like this:

override fun onBackPressed() {
        val count = supportFragmentManager.backStackEntryCount
        if(count == 0) {
            // Dialog to ask the user if he want to quit the application
        else{
            super.onBackPressed()
        }
    }

But when I press the back button while I am in the second Activity everytime the count of the BackStack is 0. When I remove the if statement and only call super.onBackPressed() the fragment in the Activity is setted back to the last fragment so I assume that the BackStack is working. How do I get the value of the BackStackCount?

Edit: In both of my Activities I have multiple Fragments.

Thank you for your help!

question from:https://stackoverflow.com/questions/65829969/android-kotlin-get-the-count-of-the-backstack-in-a-second-activity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to get the fragment backstack entry count, while you are in activity. So since you have no fragments, the backstack count is 0 for fragments.

You can try and use the activity manager like this:

ActivityManager m = (ActivityManager) ctx.getSystemService( ctx.ACTIVITY_SERVICE );
List<RunningTaskInfo> runningTaskInfoList =  m.getRunningTasks(10);
Iterator<RunningTaskInfo> itr = runningTaskInfoList.iterator();

while(itr.hasNext()){
    RunningTaskInfo runningTaskInfo = (RunningTaskInfo)itr.next();
    int id = runningTaskInfo.id;
    CharSequence desc= runningTaskInfo.description;
    int numOfActivities = runningTaskInfo.numActivities;
    String topActivity = runningTaskInfo.topActivity.getShortClassName();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...