Question

Is there any way in android to intercept activity method calls (just the standart ones, like "onStart. onCreate")? I have a lot of functionality that must be present in every activity in my app, and (since it uses different types of activities (List, Preferences)) the only way to do it is to create my custom extensions for every activity class, which sucks :(

P.S. I use roboguice, but since Dalvik doesn't support code generation at runtime, I guess it doesn't help much.

P.S.S. I thought about using AspectJ, but it's too much of a hassle since it requires a lot of complications (ant's build.xml and all that junk)

Was it helpful?

Solution

You could delegate all the repetitive work to another class that would be embedded in your other activities. This way you limit the repetitive work to creating this object and calling its onCreate, onDestroy methods.

class MyActivityDelegate {
    MyActivityDelegate(Activity a) {}

    public void onCreate(Bundle savedInstanceState) {}
    public void onDestroy() {}
}

class MyActivity extends ListActivity {
    MyActivityDelegate commonStuff;

    public MyActivity() {
        commonStuff = MyActivityDelegate(this);
    }

    public onCreate(Bundle savedInstanceState) {
        commonStuff.onCreate(savedInstanceState);
        // ...
    }
}

This minimalises the hassle and factorises all common methods and members of your activities. The other way to do it is to subclasse all the API's XXXActivty classes :(

OTHER TIPS

The roboguice 1.1.1 release includes some basic event support for components injected into a context. See http://code.google.com/p/roboguice/wiki/Events for more info.

For Example:

@ContextScoped
public class MyObserver {
  void handleOnCreate(@Observes OnCreatedEvent e) {
    Log.i("MyTag", "onCreated");
  }
}

public class MyActivity extends RoboActivity {
  @Inject MyObserver observer;  // injecting the component here will cause auto-wiring of the handleOnCreate method in the component.

  protected void onCreate(Bundle state) {
    super.onCreate(state); /* observer.handleOnCreate() will be invoked here */
  }
}

Take a look at http://code.google.com/p/android-method-interceptor/, it uses Java Proxies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top