android.accounts.AccountManager Java Examples

The following examples show how to use android.accounts.AccountManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Accounts.java    From cathode with Apache License 2.0 7 votes vote down vote up
public static void removeAccount(Context context) {
  try {
    AccountManager am = AccountManager.get(context);
    Account account = getAccount(context);
    ContentResolver.removePeriodicSync(account, BuildConfig.PROVIDER_AUTHORITY, new Bundle());
    ContentResolver.removePeriodicSync(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR,
        new Bundle());
    AccountAuthenticator.allowRemove();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
      am.removeAccount(account, null, null, null);
    } else {
      am.removeAccount(account, null, null);
    }
  } catch (SecurityException e) {
    Timber.e(e, "Unable to remove account");
  }
}
 
Example #2
Source File: AuthHelper.java    From android-atleap with Apache License 2.0 6 votes vote down vote up
/**
 * Recreate authToken for the specified account. Do not use this method from main thread.
 * @param context context
 * @param account account
 * @param accountType accountType
 * @param authTokenType authTokenType
 * @param requiredFeatures requiredFeatures, could be <code>null</code>
 * @param options options, could be <code>null</code>
 * @param activity activity, could be <code>null</code>
 */
public static void reCreateAuthTokenBlocking(Context context, Account account, String accountType, String authTokenType, String[] requiredFeatures, Bundle options, Activity activity) {
    boolean isAccountExist = isAccountExist(context, account);
    if (!isAccountExist) {
        addAccountBlocking(context, accountType, authTokenType, requiredFeatures, options, activity);
        return;
    }

    final AccountManager am = AccountManager.get(context);
    String authToken = am.peekAuthToken(account, authTokenType);

    if (TextUtils.isEmpty(authToken)) {
        getAuthTokenWithoutCheck(context, account, authTokenType, options, activity);
        return;
    }

    am.invalidateAuthToken(account.type, authToken);

    getAuthTokenWithoutCheck(context, account, authTokenType, options, activity);
}
 
Example #3
Source File: SubsonicFragmentActivity.java    From Audinaut with GNU General Public License v3.0 6 votes vote down vote up
private void createAccount() {
    final Context context = this;

    new SilentBackgroundTask<Void>(this) {
        @Override
        protected Void doInBackground() {
            AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
            Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
            accountManager.addAccountExplicitly(account, null, null);

            SharedPreferences prefs = Util.getPreferences(context);
            boolean syncEnabled = prefs.getBoolean(Constants.PREFERENCES_KEY_SYNC_ENABLED, true);
            int syncInterval = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SYNC_INTERVAL, "60"));

            // Add enabled/frequency to playlist syncing
            ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, syncEnabled);
            ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, new Bundle(), 60L * syncInterval);

            return null;
        }
    }.execute();
}
 
Example #4
Source File: ChatsActivity.java    From tindroid with Apache License 2.0 6 votes vote down vote up
@Override
public void onMetaSub(final Subscription<VxCard,PrivateType> sub) {
    if (sub.deleted == null) {
        if (sub.pub != null) {
            sub.pub.constructBitmap();
        }

        if (!UiUtils.isPermissionGranted(ChatsActivity.this, Manifest.permission.WRITE_CONTACTS)) {
            // We can't save contact if we don't have appropriate permission.
            return;
        }

        if (mAccount == null) {
            mAccount = Utils.getSavedAccount(AccountManager.get(ChatsActivity.this),
                    Cache.getTinode().getMyId());
        }
        if (Topic.getTopicTypeByName(sub.topic) == Topic.TopicType.P2P) {
            ContactsManager.processContact(ChatsActivity.this,
                    ChatsActivity.this.getContentResolver(),
                    mAccount, sub.pub, null, sub.getUnique(), sub.deleted != null,
                    null, false);
        }
    }
}
 
Example #5
Source File: AccountsChangedReceiver.java    From AOSP-Kayboard-7.1.2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (!AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION.equals(intent.getAction())) {
        Log.w(TAG, "Received unknown broadcast: " + intent);
        return;
    }

    // Ideally the account preference could live in a different preferences file
    // that wasn't being backed up and restored, however the preference fragments
    // currently only deal with the default shared preferences which is why
    // separating this out into a different file is not trivial currently.
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final String currentAccount = prefs.getString(
            LocalSettingsConstants.PREF_ACCOUNT_NAME, null);
    removeUnknownAccountFromPreference(prefs, getAccountsForLogin(context), currentAccount);
}
 
Example #6
Source File: DesignerNewsLogin.java    From android-proguards with Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
private void setupAccountAutocomplete() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        permissionPrimer.setVisibility(View.GONE);
        final Account[] accounts = AccountManager.get(this).getAccounts();
        final Set<String> emailSet = new HashSet<>();
        for (Account account : accounts) {
            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                emailSet.add(account.name);
            }
        }
        username.setAdapter(new ArrayAdapter<>(this,
                R.layout.account_dropdown_item, new ArrayList<>(emailSet)));
    } else {
        if (shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)) {
            setupPermissionPrimer();
        } else {
            permissionPrimer.setVisibility(View.GONE);
            shouldPromptForPermission = true;
        }
    }
}
 
Example #7
Source File: Utils.java    From kolabnotes-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static final AccountIdentifier getAccountIdentifierWithName(Context context, String account){
    String rootFolder = "Notes";
    String email = "local";
    if(account != null && !account.equals("local")) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = AccountManager.get(context).getAccountsByType(AuthenticatorActivity.ARG_ACCOUNT_TYPE);

        for (Account acc : accounts) {
            if(account.equals(accountManager.getUserData(acc, AuthenticatorActivity.KEY_ACCOUNT_NAME))){
                email = accountManager.getUserData(acc, AuthenticatorActivity.KEY_EMAIL);
                rootFolder = accountManager.getUserData(acc, AuthenticatorActivity.KEY_ROOT_FOLDER);
            }
        }
    }

    return new AccountIdentifier(email,rootFolder);
}
 
Example #8
Source File: FileUploader.java    From Cirrus_depricated with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Service clean up
 */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service" );
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;

    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);

    super.onDestroy();
}
 
Example #9
Source File: SyncAdapterHelper.java    From COCOFramework with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 */
public Account createSyncAccount(Context context) {
    // Create the account type and default account
    Account newAccount = mAccount == null ? new Account(
            ACCOUNT, ACCOUNT_TYPE) : mAccount;
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(
                    Context.ACCOUNT_SERVICE);
    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
    if (accountManager.addAccountExplicitly(newAccount, null, null)) {
        ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
        turnOnSync(newAccount);
    }
    return newAccount;
}
 
Example #10
Source File: MainPresenter.java    From Pioneer with Apache License 2.0 6 votes vote down vote up
private void fetchPioneerAccount() {
    String ACCOUNT_TYPE = "com.github.baoti";
    String AUTH_TOKEN_TYPE = "pioneer";

    accountManager.getAuthTokenByFeatures(ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null,
            getView().getActivity(), null, null,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle result = future.getResult();
                        String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
                        String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
                        String token = result.getString(AccountManager.KEY_AUTHTOKEN);
                        toaster.show(
                                String.format("Auth result - name: %s, type: %s, token: %s",
                                        name, type, token));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, null);
}
 
Example #11
Source File: OdooAccountManager.java    From hr with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Login to user account. changes active state for user.
 * Other users will be automatically logged out
 *
 * @param context
 * @param username
 * @return new user object
 */
public static OUser login(Context context, String username) {

    // Setting odoo instance to null
    App app = (App) context.getApplicationContext();
    app.setOdoo(null, null);
    // Clearing models registry
    OModelRegistry registry = new OModelRegistry();
    registry.clearAll();
    OUser activeUser = getActiveUser(context);
    // Logging out user if any
    if (activeUser != null) {
        logout(context, activeUser.getAndroidName());
    }

    OUser newUser = getDetails(context, username);
    if (newUser != null) {
        AccountManager accountManager = AccountManager.get(context);
        accountManager.setUserData(newUser.getAccount(), "isactive", "true");
        Log.i(TAG, newUser.getName() + " Logged in successfully");
        return newUser;
    }
    // Clearing old cache of the system
    OCacheUtils.clearSystemCache(context);
    return null;
}
 
Example #12
Source File: ToolBarActivity.java    From drupalfit with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addAccount(String username, String password, String authToken) {
    String accountType = "drualfit";
    String authTokenType = "drualfit";
    Account account = new Account(username, accountType);
    Bundle userdata = null;

    Intent intent = new Intent();

    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);

    if (TextUtils.isEmpty(password)) {
        boolean added = getAccountManager().addAccountExplicitly(account, password, userdata);
    } else {
        getAccountManager().setPassword(account, password);
    }

    getAccountManager().setAuthToken(account, authTokenType, authToken);

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
}
 
Example #13
Source File: AndroidAuthenticator.java    From WayHoo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount,
            mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example #14
Source File: DrawerActivityLoginTest.java    From materialistic with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAccount() {
    AccountManager.get(activity).addAccountExplicitly(new Account("existing",
            BuildConfig.APPLICATION_ID), "password", null);
    drawerAccount.performClick();
    AlertDialog alertDialog = ShadowAlertDialog.getLatestAlertDialog();
    assertNotNull(alertDialog);
    assertThat(alertDialog.getListView().getAdapter()).hasCount(1);
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();
    assertThat(alertDialog).isNotShowing();
    ((ShadowSupportDrawerLayout) Shadow.extract(activity.findViewById(R.id.drawer_layout)))
            .getDrawerListeners().get(0)
            .onDrawerClosed(activity.findViewById(R.id.drawer));
    assertThat(shadowOf(activity).getNextStartedActivity())
            .hasComponent(activity, LoginActivity.class);
}
 
Example #15
Source File: AndroidAuthenticator.java    From android-discourse with Apache License 2.0 6 votes vote down vote up
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example #16
Source File: InsertActivity.java    From coursera-android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Exit if there are no google accounts
    if (AccountManager.get(this).getAccountsByType("com.google").length == 0)
        finish();

    setContentView(R.layout.main);
    mInsertButton = findViewById(R.id.insert);

    if (!checkPermission()) {
        requestPermissions(permissions, mRequestCode);
    } else {
        onPermissionsGranted();
    }
}
 
Example #17
Source File: MainActivity.java    From cnode-android with MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    queue = Volley.newRequestQueue(this);

    accountManager = AccountManager.get(this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);

    setupSwipingLayout();
    setupTopicsView();
    setupFilter();
}
 
Example #18
Source File: SyncUtils.java    From v2ex with Apache License 2.0 6 votes vote down vote up
/**
 * Create an entry for this application in the system account list, if it isn't already there.
 *
 * @param context Context
 */
public static void createSyncAccount(Context context) {

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = AccountUtils.getActiveAccount(context);
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    accountManager.addAccountExplicitly(account, null, null);
    // Inform the system that this account supports sync
    ContentResolver.setIsSyncable(account, V2exContract.CONTENT_AUTHORITY, 1);
    // Inform the system that this account is eligible for auto sync when the network is up
    ContentResolver.setSyncAutomatically(account, V2exContract.CONTENT_AUTHORITY, true);

    Bundle extras = new Bundle();

    extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    extras.putBoolean(SyncAdapter.EXTRA_SYNC_REMOTE, true);

    // Recommend a schedule for automatic synchronization. The system may modify this based
    // on other scheduled syncs and network utilization.
    ContentResolver.addPeriodicSync(
            account, V2exContract.CONTENT_AUTHORITY, extras, SYNC_FREQUENCY);
}
 
Example #19
Source File: Preferences.java    From Cirrus_depricated with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create the preference for allow adding new accounts
 */
private void createAddAccountPreference() {
    Preference addAccountPref = new Preference(this);
    addAccountPref.setKey("add_account");
    addAccountPref.setTitle(getString(R.string.prefs_add_account));
    mAccountsPrefCategory.addPreference(addAccountPref);

    addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AccountManager am = AccountManager.get(getApplicationContext());
            am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this,
                    null, null);
            return true;
        }
    });

}
 
Example #20
Source File: DummyAccountService.java    From ChannelSurfer with MIT License 6 votes vote down vote up
@Override
public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse,
                         String s, String s2, String[] strings, Bundle options) throws NetworkErrorException {
    Log.d(TAG, "Trying to add an account");
    final AccountManager accountManager = AccountManager.get(getApplicationContext());
    String ACCOUNT_NAME = getApplicationContext().getString(R.string.app_name);
    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_NAME);
    Log.d(TAG, accounts.length+"accounts");
    Log.d(TAG, accounts[0].toString());
    if(accounts.length > 0) {
        final Intent intent = new Intent(getApplicationContext(), DummyAccountIgnoreActivity.class);
        intent.putExtra(DummyAccountIgnoreActivity.INTENT_ACTION, DummyAccountIgnoreActivity.ACTION_ADD);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
    } else {
        return null;
    }
}
 
Example #21
Source File: DetailActivity.java    From kolabnotes-android with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if(toolbar != null){
        toolbar.setTitle("");
    }

    detailFragment = (DetailFragment)getFragmentManager().findFragmentById(R.id.detail_fragment);

    Intent startIntent = getIntent();
    String uid = startIntent.getStringExtra(Utils.NOTE_UID);
    String notebook = startIntent.getStringExtra(Utils.NOTEBOOK_UID);

    detailFragment.setStartNotebook(notebook);
    detailFragment.setStartUid(uid);

    String action = startIntent.getAction();
    if (Intent.ACTION_SEND.equals(action)) {
        AccountManager accountManager = AccountManager.get(this);
        Account[] accounts = AccountManager.get(this).getAccountsByType(AuthenticatorActivity.ARG_ACCOUNT_TYPE);
    }
}
 
Example #22
Source File: UiUtils.java    From tindroid with Apache License 2.0 5 votes vote down vote up
static void updateAndroidAccount(final Context context, final String uid, final String secret,
                                 final String token, final Date tokenExpires) {
    final AccountManager am = AccountManager.get(context);
    final Account acc = Utils.createAccount(uid);
    // It's OK to call even if the account already exists.
    am.addAccountExplicitly(acc, secret, null);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        am.notifyAccountAuthenticated(acc);
    }
    if (!TextUtils.isEmpty(token)) {
        am.setAuthToken(acc, Utils.TOKEN_TYPE, token);
        am.setUserData(acc, Utils.TOKEN_EXPIRATION_TIME, String.valueOf(tokenExpires.getTime()));
    }
}
 
Example #23
Source File: PhilHackerNewsApplication.java    From PhilHackerNews with MIT License 5 votes vote down vote up
/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 */
private static Account createSyncAccount(Context context) {
    // Create the account type and default account
    Account newAccount = new Account(ACCOUNT_NAME, ACCOUNT_TYPE);
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
    Account[] accountsByType = accountManager.getAccountsByType(ACCOUNT_TYPE);
    if (!dummyAccountAlreadyAdded(accountsByType)) {
        accountManager.addAccountExplicitly(newAccount, null, null);
    }
    return newAccount;
}
 
Example #24
Source File: Authenticator.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Bundle hasFeatures(final AccountAuthenticatorResponse response, final Account account, final String[] features) throws NetworkErrorException {
    // This call is used to query whether the Authenticator supports
    // specific features. We don't expect to get called, so we always
    // return false (no) for any queries.
    final Bundle result = new Bundle();
    result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
    return result;
}
 
Example #25
Source File: AuthenticationUtil.java    From palmsuda with Apache License 2.0 5 votes vote down vote up
public synchronized static void saveEditAccount(Context context,
		Account account) {
	if (mAccount == null) {
		Log.e(TAG, "saveEditAccount: mAccount is empty!");
		return;
	}
	AccountManager mAccountManager = AccountManager.get(context);
	mAccountManager.setPassword(account, mAccount.getAccountName());

	mAccountManager.setUserData(account, Params.PARAMS_LOGIN_PW,
			mAccount.getPassword());
	mAccountManager.setUserData(account, Params.PARAMS_LOGIN_ID,
			mAccount.getAccountName());
	mAccountManager.setUserData(account, Params.PARAMS_LOGIN_IMSI,
			mAccount.getImsi());
	mAccountManager.setUserData(account, Params.PARAMS_USER_BIRTHDAY,
			mAccount.getBirthDate());
	mAccountManager.setUserData(account, Params.PARAMS_USER_CITY,
			mAccount.getCityName());
	mAccountManager.setUserData(account, Params.PARAMS_USER_EMAIL,
			mAccount.getEmail());
	mAccountManager.setUserData(account, Params.PARAMS_USER_NICK_NAME,
			mAccount.getNickname());
	mAccountManager.setUserData(account, Params.PARAMS_USER_DESC,
			mAccount.getMkeywords());
	mAccountManager.setUserData(account, Params.PARAMS_USER_SEX,
			String.valueOf(mAccount.getSex()));
	mAccountManager.setUserData(account, Params.PARAMS_NEW_MOBILE_NUMBER,
			mAccount.getNewNum());

}
 
Example #26
Source File: NGWLoginActivity.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void finish()
{
    if (mAccountAuthenticatorResponse != null) {
        // send the result bundle back if set, otherwise send an error.
        if (mResultBundle != null) {
            mAccountAuthenticatorResponse.onResult(mResultBundle);
        } else {
            mAccountAuthenticatorResponse.onError(
                    AccountManager.ERROR_CODE_CANCELED, getString(R.string.canceled));
        }
        mAccountAuthenticatorResponse = null;
    }
    super.finish();
}
 
Example #27
Source File: OAuthAuthenticator.java    From auth with MIT License 5 votes vote down vote up
@NonNull
private Bundle createResultBundle(@NonNull Account account, String authToken) {
    final Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
    return result;
}
 
Example #28
Source File: FileActivity.java    From Cirrus_depricated with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invalidates the credentials stored for the current OC account and requests new credentials to the user,
 * navigating to {@link AuthenticatorActivity}
 *
 * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter
 *                to make the method accessible to {@link android.content.BroadcastReceiver}s.
 */
protected void requestCredentialsUpdate(Context context) {

    try {
        /// step 1 - invalidate credentials of current account
        OwnCloudClient client;
        OwnCloudAccount ocAccount =
                new OwnCloudAccount(getAccount(), context);
        client = (OwnCloudClientManagerFactory.getDefaultSingleton().
                removeClientFor(ocAccount));
        if (client != null) {
            OwnCloudCredentials cred = client.getCredentials();
            if (cred != null) {
                AccountManager am = AccountManager.get(context);
                if (cred.authTokenExpires()) {
                    am.invalidateAuthToken(
                            getAccount().type,
                            cred.getAuthToken()
                    );
                } else {
                    am.clearPassword(getAccount());
                }
            }
        }

        /// step 2 - request credentials to user
        Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
        updateAccountCredentials.putExtra(
                AuthenticatorActivity.EXTRA_ACTION,
                AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(updateAccountCredentials);

    } catch (com.synox.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
        Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show();
    }

}
 
Example #29
Source File: MainActivity.java    From SimpleDialogFragments with Apache License 2.0 5 votes vote down vote up
public void showEmailInput(View view){

        // email suggestion from registered accounts
        ArrayList<String> emails = new ArrayList<>(0);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && view != null) {
                requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_ACCOUNTS_PERMISSION);
                return;
            }
        } else {
            Account[] accounts = AccountManager.get(this).getAccounts();
            for (Account account : accounts) {
                if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                    emails.add(account.name);
                }
            }
        }

        SimpleFormDialog.build()
                .fields(Input.email(EMAIL)
                        .required()
                        .suggest(emails)
                        .text(emails.size() > 0 ? emails.get(0) : null),
                        Hint.plain(R.string.email_address_from_accounts)
                )
                .show(this, EMAIL_DIALOG);

        /** Results: {@link MainActivity#onResult} **/

    }
 
Example #30
Source File: OAuthAuthenticatorTest.java    From auth with MIT License 5 votes vote down vote up
@Test
public void accessTokenReturnedImmediately() {
    am.addAccountExplicitly(account, null, null);
    final String accessToken = "access1";
    am.setAuthToken(account, tokenType, accessToken);

    // when
    Bundle result = getAuthTokenWithResponse();

    // then
    assertNotNull(result);
    assertEquals(accessToken, result.getString(AccountManager.KEY_AUTHTOKEN));
}