سؤال

Im authenticating users in my App using AccountManager

I know that i can call getAuthTokenByFeatures and if no account is setup for my particular accountType it launches my LoginActivity which is exactly what i want ,

i have a BaseActivity which does that on the onCreate method however upon launching the LoginActivity the old activity is still on the stack and thus by pressing the back button the user can go back to the previous activity is is a behaviour i don't want, the code i have on the BaseActibity.onCreate is the following

    AccountManager manager = AccountManager.get(getBaseContext());

    manager.getAuthTokenByFeatures(
            AccountGeneral.ACCOUNT_TYPE,
            AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS,
            null,
            this,
            null,
            null,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bnd = null;
                    try {
                        bnd = future.getResult();
                        final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);

                        LOGV(TAG, "GetTokenForAccount Bundle is " + bnd);

                    } catch (Exception e) {
                        LOGE(TAG, "exception while getAuthTokenByFeatures", e);
                    }
                }
            }
            , null);

The question is: how can i disable that back behavior ? if it was me programmaticly calling the LoginActivity i would simply call finish() on the BaseActivity

هل كانت مفيدة؟

المحلول

On your AccountAuthenticatorActivity you can override the back button behavior:

@Override
public void onBackPressed() {
    Intent result = new Intent();
    Bundle b = new Bundle();
    result.putExtras(b);

    setAccountAuthenticatorResult(null); // null means the user cancelled the authorization processs
    setResult(RESULT_OK, result);
    finish();
}

Now you can react to this cancellation. In your code:

            @Override
            public void run(AccountManagerFuture<Bundle> future) {
                Bundle bnd = null;
                try {
                    if (future.isCancelled()) {
                        // Do whatever you want. I understand that you want to close this activity,
                        // so supposing that mActivity is your activity:
                        mActivity.finish();
                        return;
                    }
                    bnd = future.getResult();

                    final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);

                    LOGV(TAG, "GetTokenForAccount Bundle is " + bnd);

                } catch (Exception e) {
                    LOGE(TAG, "exception while getAuthTokenByFeatures", e);
                }
            }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top