android 中有什么方法可以拦截 Activity 方法调用(只是标准方法调用,如“onStart.onCreate”)? 我有很多功能必须出现在我的应用程序的每个 Activity 中,并且(因为它使用不同类型的 Activity (列表,首选项))唯一的方法是为每个 Activity 类创建我的自定义扩展,这糟透了:(
附言我使用 roboguice,但由于 Dalvik 不支持在运行时生成代码,所以我想它没有太大帮助。
附言我考虑过使用 AspectJ,但它太麻烦了,因为它需要很多复杂的东西(ant 的 build.xml 和所有那些垃圾)
最佳答案
roboguice 1.1.1 版本包括一些对注入(inject)到上下文中的组件的基本事件支持。参见 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 */
}
}
关于android - Activity 拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4721697/