Reputation: 42690
Usually, in order to launch a new Activity and get its result, from an Activity class, I will use
public void startActivityForResult (Intent intent, int requestCode)
However, what if I try to launch a new Activity and get its result, from a non-Activity class? How I can achieve this?
The reason I ask so as I am currently having LoginManager
class (A non-Activity class). It is having the following code.
accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true, new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
try {
Bundle bundle = future.getResult();
if (bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
// Compilation error, as LoginManager doesn't have startActivityForResult method.
startActivityForResult(intent, REQUEST_AUTHENTICATE);
Upvotes: 0
Views: 2594
Reputation: 504
Perhaps you could just send a reference to your Context
into the LoginManager
class and use it to start the Activity
?
Upvotes: 0
Reputation: 28093
((Activity) mContext).startActivityForResult(.....)
will do the trick.
But results will be delivered to the actual activity holding the context.
You can apply following Approach
Create single argument constructor in LoginManager class like follows.
class LoginManager
{
private Context mContext;
LoginManager(Context mContext)
{
this.mContext=mContext;
}
.............................
//Then whenever you want to call method call like this.
((Activity) mContext).startActivityForResult(.....)
}
Now in Activity class whenever you will create Object of LoginManager class create as follows.
LoginManager loginManager=new LoginManager(ActivityName.this);
Upvotes: 3
Reputation: 786
I would have the Activities within your project extend some kind of a "BaseActivity". Within that base activity, I would override onActivityResult() and pass the result into the LoginManager from there.
This will have the consequence of making all of your Activities pass their results to your LoginManager, so you won't have to keep overriding onActivityResult manually everywhere.
Upvotes: 0