在安卓中有没有办法拦截activity方法调用(只有标准的调用,比如"onStart. onCreate")?我有很多必须出现在我的应用程序中的每个activity中的功能(因为它使用不同类型的activity (列表、首选项)),唯一的方法是为每个activity类创建自定义扩展,这很糟糕:(
另外,我使用的是roboguice,但由于Dalvik不支持在运行时生成代码,所以我猜它没有太大帮助。
另外,我考虑过使用AspectJ,但它太麻烦了,因为它需要很多复杂性(蚂蚁的build.xml和所有的垃圾)
发布于 2011-01-21 20:12:12
您可以将所有重复性工作委托给嵌入到其他活动中的另一个类。这样,您就可以将重复性工作限制为创建此对象并调用其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-02-12 16:18:06
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 */
}
}发布于 2013-01-31 12:31:23
看看http://code.google.com/p/android-method-interceptor/,它使用了Java代理。
https://stackoverflow.com/questions/4721697
复制相似问题