【问题标题】:Communication between activity and separate class活动和单独类之间的通信
【发布时间】:2016-10-19 00:18:37
【问题描述】:

我有一个活动:

public class MyActivity extends Activity {

    @Override
    protected void onDestroy() {
// TODO: send event to other class
    }
}

还有一个单独的类:

    public class MyClass{
        MyClass(Context context){
          // I have the context of activity
        }

// This needs to be called by MyActivity in all other instantiates
        void onActivityDestroy(){

        }
    }

MyClass 在其他地方被实例化,我希望在这些实例中调用 onActivityDestroy。 MyClass 实例化的地方无法访问。

我正在寻找一种使用接口、侦听器、消息...而不是静态字段的解决方案。

【问题讨论】:

  • 为什么不调用 MyClass cs = new MyClass(); cs.onActivityDestry();在你的活动 onDestroy() 方法中。
  • MyClass 在其他地方被实例化,我需要在那里运行 onActivityDestroy。不在我创建的实例中。
  • 我不认为这是期望的行为,他们想调用 MyActivity 的 onDestroy 方法,而不是 MyClass。
  • 您可能想问如何从 MyClass 的构造函数中获取 MyActivity 的实例。看这里:stackoverflow.com/questions/9723106/get-activity-instance
  • 这正是我到目前为止所做的,但我想避免使用“静态”,尤其是避免使用静态上下文。

标签: android interface listener handler


【解决方案1】:

您可以在应用程序级别维护MyClass 实例列表,然后在OnDestroy 活动方法中访问该列表。并执行每个实例的onActivityDestroy()版本。

您应该在 Application 类中维护实例列表,每当创建 MyClass 实例时,将该实例推送到在 Application 类维护的列表中

// this is to push the MyClass instance.
Context.getApplication().getMyClassInstanceList().add(new MyClass());

public class MyActivity extends Activity {

  @Override 
  protected void onDestroy() { 
    List<Myclass> myClassObjects = Context.getApplication.getMyClassInstaceList();

    for(Myclass myclass : myClassObjects)
     {
          myclass.onActivityDestroy();
     }
   }
 }

【讨论】:

    猜你喜欢
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多