Frage

Gibt es eine Möglichkeit in Android zu Intercept Aktivität Methodenaufrufe (nur die standart diejenigen, wie "onStart. OnCreate")? Ich habe eine Menge von Funktionen, die in jeder Aktivität in meiner App vorhanden sein muss, und den einzigen Weg (da es verschiedene Arten von Aktivitäten (List, Einstellungen) verwendet), es zu tun ist meine individuellen Erweiterungen für jede Aktivität Klasse zu erstellen, die saugt: (

P. S. Ich benutze roboguice, aber da Dalvik keine Codegenerierung zur Laufzeit unterstützen, ich denke, es hilft nicht viel.

P.S.S. Ich dachte über AspectJ verwenden, aber es ist zu viel Aufwand, da es eine Menge von Komplikationen erfordert (Ameise build.xml und alles, was Junk)

War es hilfreich?

Lösung

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 :(

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top