Issue
Long story short: I am currently working on a small android game. One feature is being able to change the app theme. When the user changes the theme, an event is broadcasted throughout the app and all active activities call recreate() to apply the new theme.
The problem: Let's say there is a stack of activities: A, B, C. All activities will receive the event in the order they were opened and call recreate(). These are the lifecycle events that will get called (in order):
- Activity A will call onDestroy(), onCreate(), onStart(), onResume() and onPause()
- Activity B will call onDestroy(), onCreate(), onStart(), onResume() and onPause()
- Activity C will call onPause(), onStop(), onDestroy(), onCreate(), onStart(), onResume().
Note that neither activity A or B called onStop(). When those activities are being returned to (eg. back button press), they will not call onStart() when they become visible, but will call onResume(). This is contrary to what is stated in the activity lifecycle documentation.
The question: Is there something I'm doing wrong here? Is there another way to restart all activities in an application without messing up the activity lifecycle?
Solution
I think you are taking the wrong approach here. You should not use the framework calls in order to change your theme. The issue you are having is that you are not calling onStop
as the framework would, but even so...
The primary reason your approach is incorrect is that Android may have already destroyed an Activity
if it is not visible. So sending events to it that call framework methods is not only unnecessary at that point, but it could result in unpredictable states and behavior. Could even cause a crash.
For changes to your theme or any UI component, you should handle that in onResume
- in other words handle changes to the UI elements when the user returns to the Activity
. One option for doing this is passing flags through startActivityForResult
.
Better, make your theme selection persist using sharedPreferences
(or using another method) and then read from that when the Activity
is resumed. This would ensure the proper theme is selected regardless of how the user gets to the Activity
.
EDIT:
Note that the Activity
framework methods are public
not because they should be accessed at any time or by other classes, but because that is required for them to be implemented in your app. They are not intended to be invoked outside the framework.
You should note that in the official documentation for Activity
none of the methods you are calling are listed as "Public Methods" (http://developer.android.com/reference/android/app/Activity.html#Activity()). You are using them in an unsupported way. However, I only point this out to make you aware of it and that it is not a generally accepted approach to solving this problem.
Answered By - Jim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.