从非活动中使用 startActivityForResult

我有 MainActivity,它是一个 Activity 和其他类(它是一个简单的 java 类) ,我们称之为“ SimpleClass”。

现在我想从这个类运行命令 startActivityForResult

我认为我可以只使用 MainActivity 的上下文传递那个类(SimpleClass) ,但问题是我们不能运行 context.startActivityForResult(...);

因此,使 SimpleClass 使用 startActivityForResult的唯一方法是将 MainActivity 作为 Activity 变量的引用传递给 SimpleClass。

差不多是这样:

在 MainActivity 类中,我像这样创建了 SimpleClass 的实例:

SimpleClass simpleClass = new SimpleClass(MainActivity.this);

现在,这就是 SimpleClass 的样子:

public Class SimpleClass {


Activity myMainActivity;


public SimpleClass(Activity mainActivity) {
super();
this.myMainActivity=mainActivity;
}
....




public void someMethod(...) {
myMainActivity.startActivityForResult(...);
}


}

现在起作用了,但是没有合适的方法吗?我担心将来可能会有一些内存泄漏。

65311 次浏览

If you need to get the result from the previous Activity, then your calling class needs to be of type Activity.

What is the purpose of you calling Activity.startActivityForResult() if you never use the result (at least according to the sample code you posted).

Does myMainActivity do anything with the result? If so, then just make SimpleClass a subclass of Activity and handle the result from within SimpleClass itself.
If myMainActivity needs the result, then maybe you should refactor the code to start the activity from myMainActivity.

Better solution is :

  1. Making SimpleClass a subclass of your Activity class
  2. calling another Activity as startActivityForResult
  3. handling the result within SimpleClass itself

I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.

Try this:

if (mContext instanceof Activity) {
((Activity) mContext).startActivityForResult(...);
} else {
Log.e("mContext should be an instanceof Activity.");
}

This should compile, and the results should be delivered to the actual activity holding the context.