Issue
I know we can keep only one instance by
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
but I need that my app can create maximum two instances of certain activity not more than that.
I am using a chained search feature like image below
When Instance3 of the activity1 is created i want to destroy:-
- Instance1 of activity1
- Instance1 of activity2
Tried to used this to kill a specific activity but activity have same Pid for all processes in an app
android.os.Process.killProcess( stack.getLast());
is there a way we can moderate which instances should be kept alive?
any help would be great thanks!
Solution
In my opinion this is the wrong architecture. For chained search you should only ever have a single instance of each Activity
. You should flip between the different Activity
instances by calling startActivity()
and setting Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
in the Intent
you use. Also add the data you want to display as "extras" in the Intent
.
To be able to use the BACK button to back through the chain (no matter how long it is), each Activity
should manage a stack that contains the data that it needs to recreate the page whenever the user backs into it. In onCreate()
and in onNewIntent()
the data (from the "extras") should be pushed onto the stack and displayed. You then override onBackPressed()
and go back to the previous Activity
by calling startActivity()
, and setting Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
in the Intent
you use. You also add an "extra" to the Intent
that indicates the user wants to "go back". In onBackPressed()
you should also discard the top element off the data stack of the Activity
that is being left. This will ensure that the stack is correct when the user then backs into this Activity
.
In onNewIntent()
if the user just backed into the Activity
, you just display the data that is already on top of the stack of managed data.
In this way, you only ever have one instance of each Activity
, the user can chain all day through the set of activities and the BACK button always works and you don't have to worry about running out of memory.
Trying to accomplish this using taskAffinity
or Intent
flags or similar will not work. Don't waste your time. It is also bad programming style.
I hope this is clear.
Answered By - David Wasser
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.