chubbsondubs
chubbsondubs

Reputation: 38857

Is there a way to intercept Android Activity after it is instantiated?

Is there a way to intercept whenever the Application creates a new Activity instance? I'm only interested in Activities belonging to the Application process not all Activities on the phone. Is there some way to do this? Is the Application class involved in doing this in some way? What methods can I override to get at the Activity instance after it's been created?

Upvotes: 0

Views: 816

Answers (1)

Vit Khudenko
Vit Khudenko

Reputation: 28418

Ok, just an idea - in your app you can create a base activity class so all the rest of activities are subclassed from that base activity. Then in the onCreate() callback you may notify some listener instance about the fact of a new app activity instance creation:

public class BaseActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // put the code to notify a listener here
    }

}

public class YourWorkingActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
    }
}

If you use a ListActivity (that is common for an average Android app), then you should also create a similar BaseListActivity for it.

Most likely the best candidate for a listener would be an Application subclass since it is guaranteed by the OS that is will be created before any Activity will be instantiated.

Warning: you should avoid keeping a strong reference to an Activity in the listener since it will create a memory leak when the OS will try to kill that Activity (as a part of the Activity or Process life-cycle). Probably use WeakReference for this.

Upvotes: 2

Related Questions