开发者

Use startActivityForResult from non-activity

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.

I though that I could pass that class (SimpleClass), using only MainActivity's context, but the problem is that we can't run context.startActivityForResult(...);.

So, the only way making SimpleClass to use startActivityForResult, is to pass th开发者_JAVA百科e reference of MainActivity as an Activity variable to the SimpleClass.

Something like that:

Inside the MainActivity class I created the instance of SimpleClass like this way:

SimpleClass simpleClass = new SimpleClass(MainActivity.this);

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(...);
    }

}

Now it's working, but isn't there a proper way of doing this? I am afraid I could have some memory leaks in the future.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜