【问题标题】:Activity interceptor活动拦截器
【发布时间】:2011-01-18 07:57:28
【问题描述】:

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

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

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

【问题讨论】:

    标签: android guice roboguice


    【解决方案1】:

    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 */
      }
    }
    

    【讨论】:

      【解决方案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 类进行子类化:(

      【讨论】:

      • 这样我仍然需要对所有活动进行子类化以调用委托方法(我现在实际实现它的方式)。我试图避免的事情是创建子活动。无论如何感谢您的回复。
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-22
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 2014-03-10
        相关资源
        最近更新 更多