Activity restart every time when disable permissio

2020-03-19 03:20发布

问题:

I am developing an android app with structure: MainActivity->FragmentA->FragmentB->Fragment C

Now in Fragment C, I go to Permission Setting and make access Camera to Deny, then I return an App. I realize that app restarted (transit to Fragment A). May you give me any reason and suggestion to solve it.

回答1:

When you revoke permissions from app settings - Activity restarts and all it's components too. But in onCreate(...) savedInstanceState doesn't equal to null.

Thus you can use such hack:

if (savedInstanceState != null) {

}

Using the above hack app resume last fragmentC.



回答2:

This is something normal and expected in AOSP. Android kills the app process while saving all states and fragments in FragmentManager, so you should retrieve back your fragment from the FragmentManager you were commiting tour fragments to. See an example approach:

// Try to retrieve fragment from fragment manager
ExampleFragment exampleFragment = (ExampleFragment) getSupportFragmentManager().findFragmentByTag("ExampleFragment");
// Fragment was not saved in fragment manager, create a new instance
if (exampleFragment == null) exampleFragment = ExampleFragment.newInstance();

Note that I'm using getSupportFragmentManager() as an example here (in the activity) but you have to use getChildFragmentManager() within fragments.