Search in sources :

Example 1 with AccountManagerFuture

use of android.accounts.AccountManagerFuture in project iNaturalistAndroid by inaturalist.

the class SignInTask method signIn.

public void signIn(INaturalistService.LoginType loginType, String username, String password, boolean invalidated) {
    boolean googleLogin = (loginType == INaturalistService.LoginType.GOOGLE);
    if (googleLogin) {
        String googleUsername = null;
        Account account = null;
        // See if given account exists
        final Account[] availableAccounts = AccountManager.get(mActivity).getAccountsByType("com.google");
        boolean accountFound = false;
        if (username != null) {
            googleUsername = username.toLowerCase();
            for (int i = 0; i < availableAccounts.length; i++) {
                if (availableAccounts[i].name.equalsIgnoreCase(googleUsername)) {
                    // Found the account
                    // Log.d(TAG, "googleUsername: " + googleUsername);
                    accountFound = true;
                    break;
                }
            }
        }
        final String boundUsername = googleUsername;
        final String boundInvalidated = invalidated ? "invalidated" : null;
        final AccountManagerCallback<Bundle> cb = new AccountManagerCallback<Bundle>() {

            public void run(AccountManagerFuture<Bundle> future) {
                try {
                    final Bundle result = future.getResult();
                    final String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
                    final String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
                    final Intent authIntent = result.getParcelable(AccountManager.KEY_INTENT);
                    if (accountName != null && authToken != null) {
                        // Log.d(TAG, String.format("Token: %s", authToken));
                        execute(boundUsername, authToken, INaturalistService.LoginType.GOOGLE.toString(), boundInvalidated);
                    } else if (authIntent != null) {
                        int flags = authIntent.getFlags();
                        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                        authIntent.setFlags(flags);
                        mActivity.startActivityForResult(authIntent, REQUEST_CODE_LOGIN);
                    } else {
                        Log.e(TAG, "AccountManager was unable to obtain an authToken.");
                    }
                } catch (Exception e) {
                    Log.e(TAG, "Auth Error", e);
                }
            }
        };
        if (availableAccounts.length > 1) {
            // More than one Google account - Show multiple choice to select account
            List<String> emails = new ArrayList<String>();
            for (int i = 0; i < availableAccounts.length; i++) {
                emails.add(availableAccounts[i].name);
            }
            mHelper.selection(mActivity.getString(R.string.select_google_account), emails.toArray(new String[emails.size()]), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    AccountManager.get(mActivity).getAuthToken(availableAccounts[which], GOOGLE_AUTH_TOKEN_TYPE, null, mActivity, cb, null);
                }
            });
            return;
        } else if (availableAccounts.length == 1) {
            accountFound = true;
            account = availableAccounts[0];
        } else if (googleUsername == null) {
            askForGoogleEmail();
            return;
        } else {
            // Redirect user to add account dialog
            mGoogleUsername = googleUsername;
            mActivity.startActivityForResult(new Intent(Settings.ACTION_ADD_ACCOUNT), REQUEST_CODE_ADD_ACCOUNT);
            return;
        }
        if (account == null) {
            account = new Account(googleUsername, "com.google");
        }
        AccountManager.get(mActivity).getAuthToken(account, GOOGLE_AUTH_TOKEN_TYPE, null, mActivity, cb, null);
    } else {
        // "Regular" login
        execute(username, password, INaturalistService.LoginType.OAUTH_PASSWORD.toString());
    }
}
Also used : Account(android.accounts.Account) AccountManagerCallback(android.accounts.AccountManagerCallback) DialogInterface(android.content.DialogInterface) Bundle(android.os.Bundle) ArrayList(java.util.ArrayList) Intent(android.content.Intent) AccountManagerFuture(android.accounts.AccountManagerFuture) JSONException(org.json.JSONException) FacebookException(com.facebook.FacebookException)

Example 2 with AccountManagerFuture

use of android.accounts.AccountManagerFuture in project Reader by TheKeeperOfPie.

the class ActivityMain method addNewAccount.

public void addNewAccount() {
    accountManager.addAccount(Reddit.ACCOUNT_TYPE, Reddit.AUTH_TOKEN_FULL_ACCESS, null, null, this, new AccountManagerCallback<Bundle>() {

        @Override
        public void run(final AccountManagerFuture<Bundle> future) {
            Observable.just(future).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).flatMap(UtilsRx.flatMapWrapError(AccountManagerFuture::getResult)).observeOn(AndroidSchedulers.mainThread()).subscribe(new FinalizingSubscriber<Bundle>() {

                @Override
                public void next(Bundle next) {
                    super.next(next);
                    String name = next.getString(AccountManager.KEY_ACCOUNT_NAME);
                    Account[] accounts = accountManager.getAccountsByType(Reddit.ACCOUNT_TYPE);
                    for (Account account : accounts) {
                        if (account.name.equals(name)) {
                            setAccount(account);
                            break;
                        }
                    }
                }

                @Override
                public void error(Throwable e) {
                    super.error(e);
                    Toast.makeText(ActivityMain.this, R.string.error_account, Toast.LENGTH_LONG).show();
                }

                @Override
                public void finish() {
                    super.finish();
                    resetAccountList();
                }
            });
        }
    }, null);
}
Also used : Account(android.accounts.Account) Bundle(android.os.Bundle) AccountManagerFuture(android.accounts.AccountManagerFuture) FinalizingSubscriber(com.winsonchiu.reader.rx.FinalizingSubscriber)

Example 3 with AccountManagerFuture

use of android.accounts.AccountManagerFuture in project XPrivacy by M66B.

the class XAccountManager method after.

@Override
@SuppressWarnings("unchecked")
protected void after(XParam param) throws Throwable {
    int uid = Binder.getCallingUid();
    switch(mMethod) {
        case addOnAccountsUpdatedListener:
            // Do nothing
            break;
        case blockingGetAuthToken:
            if (param.getResult() != null && param.args.length > 0 && param.args[0] != null) {
                Account account = (Account) param.args[0];
                if (isRestrictedExtra(param, account == null ? null : account.name))
                    if (!isAccountAllowed(account, uid))
                        param.setResult(null);
            }
            break;
        case getAccounts:
            if (param.getResult() != null && isRestricted(param)) {
                Account[] accounts = (Account[]) param.getResult();
                param.setResult(filterAccounts(accounts, uid));
            }
            break;
        case getAccountsByType:
        case getAccountsByTypeForPackage:
            if (param.getResult() != null && param.args.length > 0)
                if (isRestrictedExtra(param, (String) param.args[0])) {
                    Account[] accounts = (Account[]) param.getResult();
                    param.setResult(filterAccounts(accounts, uid));
                }
            break;
        case getAccountsByTypeAndFeatures:
            if (param.getResult() != null && param.args.length > 0)
                if (isRestrictedExtra(param, (String) param.args[0])) {
                    AccountManagerFuture<Account[]> future = (AccountManagerFuture<Account[]>) param.getResult();
                    param.setResult(new XFutureAccount(future, uid));
                }
            break;
        case getAuthenticatorTypes:
            if (param.getResult() != null && isRestricted(param))
                param.setResult(new AuthenticatorDescription[0]);
            break;
        case getAuthToken:
            if (param.getResult() != null && param.args.length > 0) {
                Account account = (Account) param.args[0];
                if (isRestrictedExtra(param, account == null ? null : account.name)) {
                    AccountManagerFuture<Bundle> future = (AccountManagerFuture<Bundle>) param.getResult();
                    param.setResult(new XFutureBundle(future, uid));
                }
            }
            break;
        case getAuthTokenByFeatures:
            if (param.getResult() != null)
                if (isRestrictedExtra(param, (String) param.args[0])) {
                    AccountManagerFuture<Bundle> future = (AccountManagerFuture<Bundle>) param.getResult();
                    param.setResult(new XFutureBundle(future, uid));
                }
            break;
        case hasFeatures:
            if (param.getResult() != null && param.args.length > 0 && param.args[0] != null) {
                Account account = (Account) param.args[0];
                if (isRestrictedExtra(param, account == null ? null : account.name))
                    if (!isAccountAllowed(account, uid))
                        param.setResult(new XFutureBoolean());
            }
            break;
        case removeOnAccountsUpdatedListener:
            // Do nothing
            break;
        case Srv_getAccounts:
        case Srv_getAccountsAsUser:
        case Srv_getAccountsForPackage:
        case Srv_getSharedAccountsAsUser:
            // Filter account list
            String extra = null;
            if (mMethod == Methods.Srv_getAccounts || mMethod == Methods.Srv_getAccountsAsUser || mMethod == Methods.Srv_getAccountsForPackage)
                if (param.args.length > 0 && param.args[0] instanceof String)
                    extra = (String) param.args[0];
            if (param.getResult() instanceof Account[])
                if (isRestrictedExtra(param, extra)) {
                    Account[] accounts = (Account[]) param.getResult();
                    param.setResult(filterAccounts(accounts, uid));
                }
            break;
        case Srv_getAccountsByFeatures:
            // Do nothing
            break;
    }
}
Also used : Account(android.accounts.Account) AuthenticatorDescription(android.accounts.AuthenticatorDescription) Bundle(android.os.Bundle) AccountManagerFuture(android.accounts.AccountManagerFuture)

Example 4 with AccountManagerFuture

use of android.accounts.AccountManagerFuture in project android-delicious by lexs.

the class ContainerActivity method logout.

private void logout() {
    Log.d(TAG, "Removing account");
    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
    Account account = accounts[0];
    // Callback to wait for the account to actually be removed
    AccountManagerCallback<Boolean> callback = new AccountManagerCallback<Boolean>() {

        @Override
        public void run(AccountManagerFuture<Boolean> future) {
            try {
                if (future.getResult()) {
                    checkAccount();
                } else {
                    // Could not remove account, should not happen
                    Log.e(TAG, "Could not remove account");
                }
            } catch (Exception e) {
                Log.e(TAG, "Error fetching remove account result", e);
            }
        }
    };
    accountManager.removeAccount(account, callback, null);
}
Also used : Account(android.accounts.Account) DeliciousAccount(se.alexanderblom.delicious.DeliciousAccount) AccountManagerCallback(android.accounts.AccountManagerCallback) AccountManager(android.accounts.AccountManager) AccountManagerFuture(android.accounts.AccountManagerFuture)

Example 5 with AccountManagerFuture

use of android.accounts.AccountManagerFuture in project ChatExchange by HueToYou.

the class MainActivity method setup.

private void setup() {
    final FloatingActionMenu fam = findViewById(R.id.chat_slide_menu);
    FloatingActionButton floatingActionButton = findViewById(R.id.add_chat_fab);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mainActivityUtils.showAddTabDialog();
            fam.close(true);
        }
    });
    FloatingActionButton fab = findViewById(R.id.home_fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    Log.e("POS", "DEFL");
                    fragStuff.setFragmentByTag("home");
                }
            }, getResources().getInteger(R.integer.animation_duration_ms));
            // doCloseAnimationForDrawerToggle(mDrawerButton);
            mChatroomSlidingMenu.toggle();
            fam.close(false);
        }
    });
    mRequestFactory = new RequestFactory();
    mAccountManager = AccountManager.get(this);
    AccountManagerCallback<Bundle> accountManagerCallback = new AccountManagerCallback<Bundle>() {

        @Override
        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
            Log.e("AUtH", "AAA");
            String authToken = "";
            try {
                authToken = accountManagerFuture.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                Log.e("Auth", authToken);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("RI", "P");
            }
            mRequestFactory = new RequestFactory(authToken);
            mCookieString = authToken;
            Log.e("AUTHTOKEN", authToken);
            CookieSyncManager.createInstance(MainActivity.this);
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            if (authToken != null) {
                cookieManager.removeSessionCookie();
                cookieManager.setCookie("https://stackexchange.com", authToken);
                CookieSyncManager.getInstance().sync();
            }
            fragStuff.doFragmentStuff();
        }
    };
    Set<String> seChatsTemp = mSharedPrefs.getStringSet("SEChatIDs", new HashSet<String>());
    Set<String> soChatsTemp = mSharedPrefs.getStringSet("SOChatIDs", new HashSet<String>());
    chatDataBundle.mSOChatIDs = new HashSet<>(soChatsTemp);
    chatDataBundle.mSEChatIDs = new HashSet<>(seChatsTemp);
    if (mSharedPrefs.getBoolean("isFirstRun", true)) {
        Intent intent = new Intent(this, IntroActivity.class);
        startActivity(intent);
        finish();
    } else if (mAccountManager.getAccounts().length < 1) {
        startActivity(new Intent(this, AuthenticatorActivity.class));
        finish();
    } else {
        if (mFragmentManager.findFragmentByTag("home") == null) {
            mFragmentManager.beginTransaction().add(R.id.content_main, new HomeFragment(), "home").commit();
        }
        mAccountManager.getAuthToken(mAccountManager.getAccounts()[0], Authenticator.ACCOUNT_TYPE, null, true, accountManagerCallback, null);
    }
    mainActivityUtils.respondToNotificationClick();
    mainActivityUtils.setupACBR();
    mItemClickedListener = new RecyclerAdapter.OnItemClicked() {

        @Override
        public void onClick(View view, int position) {
            Log.e("CLICKED", position + "");
            mCurrentFragment = mWrappedAdapter.getItemAt(position).getUrl();
            // doCloseAnimationForDrawerToggle(mDrawerButton);
            getmChatroomSlidingMenu().toggle();
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    fragStuff.setFragmentByTag(mCurrentFragment);
                }
            }, getResources().getInteger(R.integer.animation_duration_ms));
        }

        @Override
        public void onCloseClick(View view, int position) {
            mainActivityUtils.confirmClose(position);
        }
    };
    chatroomsList = findViewById(R.id.chatroomsListView);
    mSwipeManager = new RecyclerViewSwipeManager();
    mWrappedAdapter = new RecyclerAdapter(this, mItemClickedListener, mSwipeManager);
    mAdapter = mSwipeManager.createWrappedAdapter(mWrappedAdapter);
    chatroomsList.setAdapter(mAdapter);
    // disable change animations
    ((SimpleItemAnimator) chatroomsList.getItemAnimator()).setSupportsChangeAnimations(false);
    mSwipeManager.attachRecyclerView(chatroomsList);
    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(chatroomsList.getContext(), DividerItemDecoration.VERTICAL);
    chatroomsList.addItemDecoration(dividerItemDecoration);
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_menu_black_24dp, null);
    drawable.setTintList(ColorStateList.valueOf(Color.rgb(255, 255, 255)));
    getSupportActionBar().setHomeAsUpIndicator(drawable);
    fam.hideMenuButton(false);
    mActionBar = (Toolbar) Utils.getActionBar(getWindow().getDecorView());
    assert mActionBar != null;
    Log.e("ACTIONBAR", mActionBar.getClass().toString());
    // mActionBar.removeViewAt(1);
    // mActionBar.addView(newDrawer, 1);
    mDrawerButton = (AppCompatImageButton) mActionBar.getChildAt(1);
    ObjectAnimator closeAnimator = ObjectAnimator.ofFloat(mDrawerButton, "rotation", 180f, 0f);
    mCloseAnimSet.play(closeAnimator);
    mCloseAnimSet.setInterpolator(new AnticipateInterpolator());
    mCloseAnimSet.setDuration((long) Utils.getAnimDuration(getResources().getInteger(R.integer.animation_duration_ms), MainActivity.this));
    ObjectAnimator openAnimator = ObjectAnimator.ofFloat(mDrawerButton, "rotation", -180f, 0f);
    mOpenAnimSet.play(openAnimator);
    mOpenAnimSet.setInterpolator(new OvershootInterpolator());
    mOpenAnimSet.setDuration((long) Utils.getAnimDuration(getResources().getInteger(R.integer.animation_duration_ms), MainActivity.this));
    mDrawerButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Log.e("CLICKED", "CLICKED");
            onSupportNavigateUp();
        }
    });
    mChatroomSlidingMenu.setOnCloseListener(new SlidingMenu.OnCloseListener() {

        @Override
        public void onClose() {
            fam.close(false);
            fam.hideMenuButton(false);
            doCloseAnimationForDrawerToggle(mDrawerButton);
        }
    });
    mChatroomSlidingMenu.setOnOpenListener(new SlidingMenu.OnOpenListener() {

        @Override
        public void onOpen() {
            doOpenAnimationForDrawerToggle(mDrawerButton);
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    fam.showMenuButton(true);
                }
            }, getResources().getInteger(R.integer.animation_duration_ms) - 400);
        }
    });
    mChatroomSlidingMenu.setOnOpenedListener(new SlidingMenu.OnOpenedListener() {

        @Override
        public void onOpened() {
            TutorialStuff.showChatSliderTutorial_MainActivity(MainActivity.this);
        }
    });
    Log.e("FEATURE", String.valueOf(getWindow().hasFeature(Window.FEATURE_OPTIONS_PANEL)));
    mActionMenuView = (ActionMenuView) mActionBar.getChildAt(2);
    oncreatejustcalled = true;
    // forces options menu overflow icon to show on devices with physical menu keys
    try {
        ViewConfiguration config = ViewConfiguration.get(this);
        Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
        if (menuKeyField != null) {
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        }
    } catch (Exception e) {
    // presumably, not relevant
    }
}
Also used : AccountManagerCallback(android.accounts.AccountManagerCallback) AccountManagerFuture(android.accounts.AccountManagerFuture) HomeFragment(com.huetoyou.chatexchange.ui.frags.HomeFragment) FloatingActionMenu(com.github.clans.fab.FloatingActionMenu) SlidingMenu(com.jeremyfeinstein.slidingmenu.lib.SlidingMenu) ViewConfiguration(android.view.ViewConfiguration) Field(java.lang.reflect.Field) RequestFactory(com.huetoyou.chatexchange.net.RequestFactory) FloatingActionButton(com.github.clans.fab.FloatingActionButton) CookieManager(android.webkit.CookieManager) RecyclerViewSwipeManager(com.h6ah4i.android.widget.advrecyclerview.swipeable.RecyclerViewSwipeManager) SimpleItemAnimator(android.support.v7.widget.SimpleItemAnimator) OvershootInterpolator(android.view.animation.OvershootInterpolator) Bundle(android.os.Bundle) ChatDataBundle(com.huetoyou.chatexchange.ui.misc.ChatDataBundle) ObjectAnimator(android.animation.ObjectAnimator) Intent(android.content.Intent) DividerItemDecoration(android.support.v7.widget.DividerItemDecoration) View(android.view.View) CustomRecyclerView(com.huetoyou.chatexchange.ui.misc.CustomRecyclerView) ActionMenuView(android.support.v7.widget.ActionMenuView) RecyclerView(android.support.v7.widget.RecyclerView) AnticipateInterpolator(android.view.animation.AnticipateInterpolator) RecyclerAdapter(com.huetoyou.chatexchange.ui.misc.RecyclerAdapter)

Aggregations

AccountManagerFuture (android.accounts.AccountManagerFuture)5 Account (android.accounts.Account)4 Bundle (android.os.Bundle)4 AccountManagerCallback (android.accounts.AccountManagerCallback)3 Intent (android.content.Intent)2 AccountManager (android.accounts.AccountManager)1 AuthenticatorDescription (android.accounts.AuthenticatorDescription)1 ObjectAnimator (android.animation.ObjectAnimator)1 DialogInterface (android.content.DialogInterface)1 ActionMenuView (android.support.v7.widget.ActionMenuView)1 DividerItemDecoration (android.support.v7.widget.DividerItemDecoration)1 RecyclerView (android.support.v7.widget.RecyclerView)1 SimpleItemAnimator (android.support.v7.widget.SimpleItemAnimator)1 View (android.view.View)1 ViewConfiguration (android.view.ViewConfiguration)1 AnticipateInterpolator (android.view.animation.AnticipateInterpolator)1 OvershootInterpolator (android.view.animation.OvershootInterpolator)1 CookieManager (android.webkit.CookieManager)1 FacebookException (com.facebook.FacebookException)1 FloatingActionButton (com.github.clans.fab.FloatingActionButton)1