0

Actually This is a question asked in interview.

I have five activities A,B,C,D and E in an android application. I open all the activities in their order as shown. Now I have to close odd activities on a button click. And this button exist in E activity.

I give one solution that I have static instance of all activities and from any activity we can close any one activity or other solution is that I can send instance of one activity to another activity by intent and in last activity we have instance of all previous activity. Now we can also close odd or even whatever activity it is.

But I think there may be some other options available which is best then above.

ParikshitSinghTomar
  • 417
  • 1
  • 4
  • 28

1 Answers1

2

I wouldn't suggest using static references to Activities. Activity instances can be very large and you will create memory leaks with static references.

The suggestion to send an instance of an Activty via Intent to another Activity doesn't work. When you send something via Intent, Android serializes and then deserializes the object. The receiver gets a copy of the object, not the original object. So you wouldn't be able to call finish() on the original object using this technique. Also, only the Android framework can properly instantiate Android components (Activity, Service, BroadcastReceiver, Provider), so you can't properly deserialize an Android component.

I would do this by using a BraodcastReceiver. Each Activity should create a BroadcastReceiver and register it to listen for some broadcast Intent. In this broadcast Intent you could put (as an extra) the class name (or names) of Activities which should exit - or maybe something like "all" if all activities should exit. When you want to cause a specific activity or list of activities to exit, you should just send a braodcast Intent with the approperiate extras. When the BraodcastReceiver'sonReceive() method runs, it can chek to see if it should exit, and if so, it can call finish().

David Wasser
  • 93,459
  • 16
  • 209
  • 274