在android中是否有任何方法可以拦截活动方法调用(只是标准的调用,如“onStart.onCreate”)? 我的应用程序中的每个活动都必须包含许多功能,并且(因为它使用不同类型的活动(列表,首选项)),唯一的方法是为每个活动类创建自定义扩展,糟透了:(
P.S。我使用roboguice,但由于Dalvik在运行时不支持代码生成,我认为它没有多大帮助。
P.S.S。我考虑过使用AspectJ,但这太麻烦了,因为它需要很多复杂功能(ant的build.xml和所有垃圾)
答案 0 :(得分: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 */
}
}
答案 1 :(得分: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类子类化:(
答案 2 :(得分:0)
看看http://code.google.com/p/android-method-interceptor/,它使用Java代理。