4

android中有什么方法可以拦截活动方法调用(只是标准的方法调用,比如“onStart.onCreate”)?我有很多功能必须存在于我的应用程序的每个活动中,并且(因为它使用不同类型的活动(列表、首选项))唯一的方法是为每个活动类创建我的自定义扩展,这糟透了:(

PS我使用roboguice,但是由于Dalvik不支持在运行时生成代码,我想它并没有多大帮助。

PSS 我考虑过使用 AspectJ,但这太麻烦了,因为它需要很多复杂性(ant 的 build.xml 和所有垃圾)

4

3 回答 3

5

roboguice 1.1.1 版本包括一些对注入上下文的组件的基本事件支持。有关详细信息,请参阅http://code.google.com/p/roboguice/wiki/Events

例如:

@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 */
  }
}
于 2011-02-12T08:18:06.077 回答
2

您可以将所有重复性工作委托给另一个嵌入到您的其他活动中的类。通过这种方式,您可以将重复工作限制为创建此对象并调用其 onCreate、onDestroy 方法。

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);
        // ...
    }
}

这最大限度地减少了麻烦,并分解了您活动的所有常用方法和成员。另一种方法是对所有 API 的 XXXActivty 类进行子类化:(

于 2011-01-21T12:12:12.093 回答
0

看看http://code.google.com/p/android-method-interceptor/,它使用 Java 代理。

于 2013-01-31T04:31:23.220 回答