Issue
I have an activity that is started from another activity via a button and which gets passed an intent when started. I now figured out, that the activity is then created several times, since it is started with an intent, and will call onCreate() every time I hit the button mentioned above. In the documentation I read it says "Every time there's a new intent for a "standard" activity, a new instance of the class is created to respond to that intent", so that I assume that I then have several instances of that activity somewhere on the stack. This is what I would like to avoid, since the activity has some static variables which are referenced from other activites and I want to make sure that the value of this variable is deterministic!
What I want is to get rid of all existing instances and create a new instance of the activity when I press the button, or make sure to have just one activity and create it with the new intent everytime.
I tried to achieve this by setting android:launchMode="singleTop" for the activity and implementing onNewIntent(intent). This should make sure that I only have one instance of the activity in this scenario and I get the new intent. However if I do it like this, I basically have to copy my whole onCreate() method, but just using the new intent, which feels wrong.
public void onNewIntent(Intent intent) {
myAdapter= null;
serverThread.stopThread();
serverThread = null;
this.onCreate(...); // <- somehow do all this with new intent
}
Do you have a good idea how to solve this situation easily?
Solution
In the above situation actually onDestroy() is called when the user is navigating back to the previous activity with the button creating the intent and starting the activity. I.e. actually in this case there is already only one instance of the activity and the previous one is being destroyed.
For this reason onNewIntent() is not called in the above setup. If you want to e.g. stop a server, as indicated above in the question by a piece of code, so that you can start a new one when pressing the button again, you hence can actually simply do this:
@Override
public void onDestroy() {
serverThread.stopThread();
super.onDestroy();
}
Hope that helps others :)
Answered By - user1809923
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.