使用startActivityForResult从非活动startActivityForResult

2023-09-12 07:14:43 作者:別拿無知當個性~

我有MainActivity这是一种活动和其他类(这是一个简单的Java类),we`ll称之为SimpleClass。 现在我想从该类运行命令startActivityForResult。

I have MainActivity which is an Activity and other class(which is a simple java class), we`ll call it "SimpleClass". now i want to run from that class the command startActivityForResult.

现在我虽然,我可以通过这个类(SimpleClass),只有MainActivity的情况下,问题在于,ü不能运行context.startActivityForResult(...);

now i though that i could pass that class(SimpleClass), only MainActivity's context, problem is that, u cant run context.startActivityForResult(...);

这样做SimpleClass使用'startActivityForResult的唯一方法;是通过MainActivity的引用作为活动变量的SimpleClass 这样的事情:

so the only way making SimpleClass to use 'startActivityForResult; is to pass the reference of MainActivity as an Activity variable to the SimpleClass something like that:

在MainActivity类中我创建SimpleClass的情况是这样的:

inside the MainActivity class i create the instance of SimpleClass this way:

SimpleClass simpleClass=new SimpleClass(MainActivity.this);

现在这是SimpleClass怎么是这样的:

now this is how SimpleClass looks like:

public Class SimpleClass {

Activity myMainActivity;

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


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

}

现在的工作,但心不是这样做的正确方法? I`am怕我可能有一些内存泄漏的未来。

now its working, but isnt a proper way of doing this? I`am afraid i could have some memory leaks in the future.

感谢。 射线。

推荐答案

我不知道这是很好的做法与否,但铸造了Context对象的活动对象编译罚款。

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

试试这个:((活动)mContext).startActivityForResult(...)

此应当编译,其结果应被递送到的实际活动保持的上下文

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