Haspemulator
Haspemulator

Reputation: 11308

How to get notified about activity's lifecycle

I'm writing a helper class for my activity, which uses an external service. Like in a standard design pattern regarding bound services, I want to bind on activity creation and unbind on activity destruction. However, I want to isolate this logic to my helper class, so that activity would only use an instance of that helper and don't call bind and unbind explicitly.

I can pass the activity to the helper class, but I cannot find any way to schedule a callback on activity's lifecycle's events - there's just no such methods in Activity class. While this most probably means that I cannot achieve what I want to, and also that it's probably not a good idea, I still want to ask the community about this. Is it possible? Is it a good idea? Is it possible to achieve similar results with some other classes (not the Activity)?

I'm new to Android development and I'm seeking for the best practices. Any ideas are appreciated.

Thanks!

EDIT: Basically, I want to be notified on activity creation and destruction. I want to be able to schedule a callback on onCreate and onDestroy methods, but from outside of the Activity. Those methods are protected and therefore inaccessible from other classes.

Upvotes: 3

Views: 685

Answers (2)

user
user

Reputation: 87064

You can use the Application.ActivityLifecycleCallbacks class. Keep in mind that the class was introduced in API level 14. For lower versions you could make hook methods in your library and require that the target Activity will call the appropriate hook method from its corresponding lifecycle method. Of course, this would be a very fragile implementation.

Upvotes: 4

robotoaster
robotoaster

Reputation: 3122

Lifecycle methods are the means to implement behaviour which will be executed when DalvikVM decides to do something with Activity (pause/resume/create/destroy), not to invoke that behaviour artificially.

If you want to externalise logic in helper/controller of some sort and be able to use service connection do initialization within ServiceConnection handler.

private ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName className,IBinder service) {
        ...init helper here...
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        ...shutdown helper here...
    }
};

then handle connections as usual.

Upvotes: 0

Related Questions