Example usage for android.accounts AccountManager get

List of usage examples for android.accounts AccountManager get

Introduction

In this page you can find the example usage for android.accounts AccountManager get.

Prototype

public static AccountManager get(Context context) 

Source Link

Document

Gets an AccountManager instance associated with a Context.

Usage

From source file:com.ntsync.android.sync.activities.ShopActivity.java

public void onVerifyComplete(PayPalConfirmationResult result) {
    boolean removePayment = false;
    AccountManager acm = AccountManager.get(this);
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);

    if (result != null) {
        LogHelper.logI(TAG, "Payment verified. Result:" + result);
        switch (result) {
        case SUCCESS:
            removePayment = true;//from   w  w  w . ja  v  a2  s  . c o m
            onPaymentSuccess(account);
            break;
        case INVALID_PRICE:
            removePayment = true;
            MessageDialog.show(R.string.shop_activity_invalidprice, this);
            break;
        case INVALID_SYNTAX:
            removePayment = true;
            MessageDialog.show(R.string.shop_activity_invalidsyntax, this);
            break;
        case CANCELED:
            removePayment = true;
            MessageDialog.show(R.string.shop_activity_paymentcanceled, this);
            break;
        case NOT_APPROVED:
        case SALE_NOT_COMPLETED:
            MessageDialog.show(R.string.shop_activity_notapproved, this);
            break;
        case VERIFIER_ERROR:
            MessageDialog.showAndClose(R.string.shop_activity_verifiererror, this);
            break;
        case ALREADY_PROCESSED:
            removePayment = true;
            MessageDialog.show(R.string.shop_activity_paymentalreadyused, this);
            break;
        case UNKNOWN_PAYMENT:
            MessageDialog.showAndClose(R.string.shop_activity_verificationfailed, this);
            // Try to validate it one more time, later.
            break;
        case AUTHENTICATION_FAILED:
            MessageDialog.showAndClose(R.string.shop_activity_authfailed, this);
            break;
        case NETWORK_ERROR:
            MessageDialog.showAndClose(R.string.shop_activity_networkerror, this);
            break;

        default:
            removePayment = true;
            LogHelper.logE(TAG, "Unknown PaymentVerificationResult:" + result, null);
            // Unknown State
            MessageDialog.showAndClose(R.string.shop_activity_verificationfailed, this);
            break;
        }
    } else {
        finish();
    }

    if (removePayment) {
        SyncUtils.savePayment(account, acm, null, null);
    }
    SyncUtils.stopPaymentVerification();
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public UserData readUserData(Context ctx, String inAuthority) {
    AccountManager am = AccountManager.get(ctx);
    Account account = new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx));
    //      final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    //      String token = am.peekAuthToken(account, authority);
    //      if (token == null) return null;
    String userDataString = am.getUserData(account, AccountManager.KEY_USERDATA);
    if (userDataString == null)
        return null;
    try {// w ww  . j  a  va 2 s .  c  om
        return UserData.valueOf(new JSONObject(userDataString));
    } catch (JSONException e) {
        return null;
    }
}

From source file:io.v.android.apps.account_manager.AccountActivity.java

private void enforceAccountExists() {
    if (AccountManager.get(this).getAccountsByType(Constants.ACCOUNT_TYPE).length <= 0) {
        String name = "Vanadium";
        Account account = new Account(name, getResources().getString(R.string.authenticator_account_type));
        AccountManager am = AccountManager.get(this);
        am.addAccountExplicitly(account, null, null);
    }//from  w  w  w .  j a  va  2 s. c o  m
}

From source file:com.ntsync.android.sync.shared.SyncUtils.java

/**
 * Checks if some PaymentData is not yet verified
 * //from  www  . j  av a  2  s. c  om
 * @param context
 * @return true if some PaymentData is open to verify
 */
public static boolean hasPaymentData(Context context) {
    boolean foundPaymentData = false;
    AccountManager acm = AccountManager.get(context);
    Account[] accounts = acm.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account account : accounts) {
        PaymentData paymentData = SyncUtils.getPayment(account, acm);
        if (paymentData != null) {
            foundPaymentData = true;
            break;
        }
    }
    return foundPaymentData;
}

From source file:com.owncloud.android.oc_framework.operations.RemoteOperation.java

/**
 * Asynchronous execution of the operation 
 * started by {@link RemoteOperation#execute(WebdavClient, OnRemoteOperationListener, Handler)}, 
 * and result posting.//from w  w w  .ja v a 2s  .  co  m
 * 
 * TODO refactor && clean the code; now it's a mess
 */
@Override
public final void run() {
    RemoteOperationResult result = null;
    boolean repeat = false;
    do {
        try {
            if (mClient == null) {
                if (mAccount != null && mContext != null) {
                    if (mCallerActivity != null) {
                        mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext,
                                mCallerActivity);
                    } else {
                        mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext);
                    }
                } else {
                    throw new IllegalStateException(
                            "Trying to run a remote operation asynchronously with no client instance or account");
                }
            }

        } catch (IOException e) {
            Log.e(TAG, "Error while trying to access to " + mAccount.name,
                    new AccountsException("I/O exception while trying to authorize the account", e));
            result = new RemoteOperationResult(e);

        } catch (AccountsException e) {
            Log.e(TAG, "Error while trying to access to " + mAccount.name, e);
            result = new RemoteOperationResult(e);
        }

        if (result == null)
            result = run(mClient);

        repeat = false;
        if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() &&
        //                    (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) {
                (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) {
            /// possible fail due to lack of authorization in an operation performed in foreground
            Credentials cred = mClient.getCredentials();
            String ssoSessionCookie = mClient.getSsoSessionCookie();
            if (cred != null || ssoSessionCookie != null) {
                /// confirmed : unauthorized operation
                AccountManager am = AccountManager.get(mContext);
                boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials);
                boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null);
                if (bearerAuthorization) {
                    am.invalidateAuthToken(mAccount.type, ((BearerCredentials) cred).getAccessToken());
                } else if (samlBasedSsoAuthorization) {
                    am.invalidateAuthToken(mAccount.type, ssoSessionCookie);
                } else {
                    am.clearPassword(mAccount);
                }
                mClient = null;
                repeat = true; // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
                result = null;
            }
        }
    } while (repeat);

    final RemoteOperationResult resultToSend = result;
    if (mListenerHandler != null && mListener != null) {
        mListenerHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend);
            }
        });
    }
}

From source file:com.owncloud.android.media.MediaService.java

/**
 * Initialize a service instance/*from   w  ww  .  j  ava2 s. com*/
 * 
 * {@inheritDoc}
 */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating ownCloud media service");

    mWifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE))
            .createWifiLock(WifiManager.WIFI_MODE_FULL, MEDIA_WIFI_LOCK_TAG);

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Configure notification channel
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        NotificationChannel mNotificationChannel;
        // The user-visible name of the channel.
        CharSequence name = getString(R.string.media_service_notification_channel_name);
        // The user-visible description of the channel.
        String description = getString(R.string.media_service_notification_channel_description);
        // Set importance low: show the notification everywhere but with no sound
        int importance = NotificationManager.IMPORTANCE_LOW;
        mNotificationChannel = new NotificationChannel(MEDIA_SERVICE_NOTIFICATION_CHANNEL_ID, name, importance);
        // Configure the notification channel.
        mNotificationChannel.setDescription(description);
        mNotificationManager.createNotificationChannel(mNotificationChannel);
    }

    mNotificationBuilder = new NotificationCompat.Builder(this);
    mNotificationBuilder.setColor(this.getResources().getColor(R.color.primary));
    mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    mBinder = new MediaServiceBinder(this);

    // add AccountsUpdatedListener
    mAccountManager = AccountManager.get(this);
    mAccountManager.addOnAccountsUpdatedListener(new OnAccountsUpdateListener() {
        @Override
        public void onAccountsUpdated(Account[] accounts) {
            // stop playback if account of the played media files was removed
            if (mAccount != null && !AccountUtils.exists(mAccount.name, MediaService.this)) {
                processStopRequest(false);
            }
        }
    }, null, false);
}

From source file:com.bjorsond.android.timeline.utilities.Utilities.java

public static Account getUserAccount(Context c) {
    AccountManager manager = AccountManager.get(c);
    Account[] accounts = manager.getAccountsByType("com.google");

    for (Account account : accounts) {
        return account;
    }/*from   www  .j av  a 2 s. c  om*/

    Account nonRegisteredAccount = new Account("test@timelineapp.no", "com.google");
    return nonRegisteredAccount;
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * Removes an account. This should be called when, e.g., the user changes
 * to a new server.//from  w w  w . j  av a2 s  .c  o  m
 * @param context
 * @param accountType
 */
public static void removeAccount(Context context, String accountType) {
    AccountManager am = AccountManager.get(context);
    am.invalidateAuthToken(accountType, SyncAdapter.AUTHTOKEN_TYPE);
    Account[] accounts = am.getAccountsByType(accountType);
    if (accounts.length != 0)
        am.removeAccount(accounts[0], null, null);
    //String authkey = getAuthKey(context);
    //return authkey == null;
}

From source file:com.cerema.cloud2.authentication.AuthenticatorActivity.java

/**
 * {@inheritDoc}// w w  w  .j  a  v  a 2  s .  c  om
 * 
 * IMPORTANT ENTRY POINT 1: activity is shown to the user
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    //Log_OC.wtf(TAG,  "onCreate init");
    super.onCreate(savedInstanceState);

    // Workaround, for fixing a problem with Android Library Suppor v7 19
    //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    if (getSupportActionBar() != null) {
        getSupportActionBar().hide();

        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    mIsFirstAuthAttempt = true;

    // bind to Operations Service
    mOperationsServiceConnection = new OperationsServiceConnection();
    if (!bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
            Context.BIND_AUTO_CREATE)) {
        Toast.makeText(this, R.string.error_cant_bind_to_operations_service, Toast.LENGTH_LONG).show();
        finish();
    }

    /// init activity state
    mAccountMgr = AccountManager.get(this);
    mNewCapturedUriFromOAuth2Redirection = null;

    /// get input values
    mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
    mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
    if (savedInstanceState == null) {
        initAuthTokenType();
    } else {
        mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);
        mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
        mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
    }

    /// load user interface
    setContentView(R.layout.account_setup);

    /// initialize general UI elements
    initOverallUi();

    mOkButton = findViewById(R.id.buttonOK);
    mOkButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onOkClick();
        }
    });

    findViewById(R.id.centeredRefreshButton).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            checkOcServer();
        }
    });

    findViewById(R.id.embeddedRefreshButton).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            checkOcServer();
        }
    });

    /// initialize block to be moved to single Fragment to check server and get info about it 
    initServerPreFragment(savedInstanceState);

    /// initialize block to be moved to single Fragment to retrieve and validate credentials 
    initAuthorizationPreFragment(savedInstanceState);

    //Log_OC.wtf(TAG,  "onCreate end");
}

From source file:com.owncloud.android.operations.RemoteOperation.java

/**
 * Asynchronous execution of the operation 
 * started by {@link RemoteOperation#execute(WebdavClient, OnRemoteOperationListener, Handler)}, 
 * and result posting./*from  www . ja v  a 2s  .c  o m*/
 * 
 * TODO refactor && clean the code; now it's a mess
 */
@Override
public final void run() {
    RemoteOperationResult result = null;
    boolean repeat = false;
    do {
        try {
            if (mClient == null) {
                if (mAccount != null && mContext != null) {
                    if (mCallerActivity != null) {
                        mClient = OwnCloudClientUtils.createOwnCloudClient(mAccount, mContext, mCallerActivity);
                    } else {
                        mClient = OwnCloudClientUtils.createOwnCloudClient(mAccount, mContext);
                    }
                } else {
                    throw new IllegalStateException(
                            "Trying to run a remote operation asynchronously with no client instance or account");
                }
            }

        } catch (IOException e) {
            Log_OC.e(TAG, "Error while trying to access to " + mAccount.name,
                    new AccountsException("I/O exception while trying to authorize the account", e));
            result = new RemoteOperationResult(e);

        } catch (AccountsException e) {
            Log_OC.e(TAG, "Error while trying to access to " + mAccount.name, e);
            result = new RemoteOperationResult(e);
        }

        if (result == null)
            result = run(mClient);

        repeat = false;
        if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() &&
        //                    (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) {
                (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) {
            /// possible fail due to lack of authorization in an operation performed in foreground
            Credentials cred = mClient.getCredentials();
            String ssoSessionCookie = mClient.getSsoSessionCookie();
            if (cred != null || ssoSessionCookie != null) {
                /// confirmed : unauthorized operation
                AccountManager am = AccountManager.get(mContext);
                boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials);
                boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null);
                if (bearerAuthorization) {
                    am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE,
                            ((BearerCredentials) cred).getAccessToken());
                } else if (samlBasedSsoAuthorization) {
                    am.invalidateAuthToken(AccountAuthenticator.ACCOUNT_TYPE, ssoSessionCookie);
                } else {
                    am.clearPassword(mAccount);
                }
                mClient = null;
                repeat = true; // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity
                result = null;
            }
        }
    } while (repeat);

    final RemoteOperationResult resultToSend = result;
    if (mListenerHandler != null && mListener != null) {
        mListenerHandler.post(new Runnable() {
            @Override
            public void run() {
                mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend);
            }
        });
    }
}