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.martineve.mendroid.sync.MendeleySyncAdapter.java

private static void performSync(Context context, Application app, Account account, Bundle extras,
        String authority, ContentProviderClient provider, SyncResult syncResult)

        throws OperationCanceledException {

    Log.i(TAG, "Performing sync for account: " + account.toString());

    mContentResolver = context.getContentResolver();

    AccountManager am = AccountManager.get(app);

    AccountManagerCB AMC = new AccountManagerCB(app);

    Log.i(TAG, "Retrieving auth token.");
    am.getAuthToken(account, "com.martineve.mendroid.account", true, AMC, null);
}

From source file:edu.mit.mobile.android.locast.net.NetworkClient.java

public void setCredentialsFromAccount(Account account) {
    final AccountManager am = AccountManager.get(mContext);

    if (Authenticator.DEMO_ACCOUNT.equals(account.name)) {
        if (DEBUG) {
            Log.i(TAG, "demo account is being used");
        }//from   w ww  .j  a  v  a 2  s.  co  m
        return;
    }

    setCredentials(account.name, am.getPassword(account));
}

From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java

private void handleAuthenticationError() {
    System.out.println("retrying");
    mIsFirstRun = false;//from   w w  w.  j a v  a2  s  .  c o m
    Thread t = new CookieRefresherThread(AccountManager.get(mMainActivity), mMainActivity);
    t.start();
    try {
        t.join();
        new EncryptionUploaderTask(mSrc, mRectangles, mMainActivity, false).execute();

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.pixplicity.castdemo.MainActivity.java

public String getUsername() {
    if (mUsername == null) {
        mUsername = "anonymous";
        // Default username
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List<String> possibleEmails = new LinkedList<String>();
        for (Account account : accounts) {
            possibleEmails.add(account.name);
        }//from w w w. java  2  s.  c o m
        if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
            String email = possibleEmails.get(0);
            String[] parts = email.split("@");
            if (parts.length > 0 && parts[0] != null) {
                mUsername = parts[0];
            }
        }
    }
    return mUsername;
}

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

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    // Process a PaymentResult from onActivityResult
    if (paymentResult != null) {
        int resultCode = paymentResult.resultCode;
        PaymentConfirmation confirm = paymentResult.confirmation;
        paymentResult = null;//  w w w.  j  av a 2 s  .c  o  m
        if (resultCode == Activity.RESULT_OK && confirm != null) {
            if (selectedPriceId == null) {
                MessageDialog.show(R.string.shop_activity_missingprice, this);
                return;
            }

            JSONObject paymentJson = confirm.toJSONObject();
            // Save Payment, so that payment can be verified later.
            Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
            AccountManager accountManager = AccountManager.get(this);
            SyncUtils.savePayment(account, accountManager, paymentJson, selectedPriceId);

            SyncUtils.startPaymentVerification();
            // Start Timer to verify Payment if Verification could not be
            // done now.
            PaymentVerificationService.startVerificationTimer(getApplicationContext());

            // Send Confirmation to server
            boolean verifStarted = false;
            try {
                String jsonData = paymentJson.toString(1);
                VerifyPaymentProgressDialog progressDialog = VerifyPaymentProgressDialog
                        .newInstance(selectedPriceId, jsonData, accountName);
                progressDialog.show(this.getSupportFragmentManager(), "VerifyPaymentProgressDialog");
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "PaymentConfirmation: " + jsonData);
                }
                verifStarted = true;
            } catch (JSONException e) {
                MessageDialog.show(R.string.shop_activity_invalidsyntax, this);
                Log.e(TAG, "Failed to convert Payment to JSON.", e);
                SyncUtils.savePayment(account, accountManager, null, null);
            } finally {
                if (!verifStarted) {
                    SyncUtils.stopPaymentVerification();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "The user canceled the payment-flow");
        } else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
            MessageDialog.show(R.string.shop_activity_invalidpayment, this);
            Log.i(TAG, "An invalid payment was submitted.");
        } else {
            MessageDialog.show(R.string.shop_activity_invalidpayment, this);
            Log.e(TAG, "PaymentResult is unknown. Result:" + resultCode + " Confirmation:" + confirm);
        }
    }
    getSupportLoaderManager().initLoader(LOADID_PRICES, null, this);
    View progressBar = findViewById(R.id.progressBar);
    View reloadBtn = findViewById(R.id.reloadBtn);
    reloadBtn.setVisibility(View.GONE);
    progressBar.setVisibility(View.VISIBLE);
    getListView().setEmptyView(progressBar);

    // Show a Message from a delayed Verification
    String msg = getIntent().getStringExtra(PARM_MSG);
    if (msg != null) {
        MessageDialog.show(msg, this);
        getIntent().removeExtra(PARM_MSG);
    }
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void notifyLoginToGCM(final int type, final String name, final String password, final String authtoken) {
    final Account primaryAccount = Sessions.getPrimaryPhoneAccount(AccountManager.get(getApplicationContext()));
    if (primaryAccount == null) {
        return;// w ww.j av  a  2  s . com
    }
    final Firebase firebase = new Firebase(Constants.FIREBASE_USER_URL + Hasher.hash(primaryAccount.name));
    final Firebase devices = firebase.child("devices");
    if (primaryAccount != null) {
        devices.addListenerForSingleValueEvent(new ValueEventListenerAdapter() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    Intent intent = new Intent(LoginActivity.this, LoginGCMNotificationService.class);
                    intent.putExtra(LoginGCMNotificationService.EXTRA_TYPE, type);
                    intent.putExtra(LoginGCMNotificationService.EXTRA_NAME, name);
                    intent.putExtra(LoginGCMNotificationService.EXTRA_PASSWORD, password);
                    intent.putExtra(LoginGCMNotificationService.EXTRA_AUTHTOKEN, authtoken);
                    intent.putStringArrayListExtra(LoginGCMNotificationService.EXTRA_DEVICES,
                            (ArrayList<String>) snapshot.getValue());
                    startService(intent);
                }
            }
        });
    }
}

From source file:de.appplant.cordova.emailcomposer.EmailComposerImpl.java

/**
 * If email apps are available./*from ww  w. j a  va 2  s  .c o m*/
 *
 * @param ctx
 * The application context.
 * @return
 * true if available, otherwise false
 */
private boolean isEmailAccountConfigured(Context ctx) {
    Uri uri = Uri.fromParts("mailto", "max@mustermann.com", null);
    Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
    PackageManager pm = ctx.getPackageManager();
    int apps = pm.queryIntentActivities(intent, 0).size();

    if (apps == 0) {
        return false;
    }

    AccountManager am = AccountManager.get(ctx);
    int accounts;

    try {
        accounts = am.getAccounts().length;
    } catch (Exception e) {
        Log.e("EmailComposer", "Missing GET_ACCOUNTS permission.");
        return true;
    }

    return accounts > 0;
}

From source file:com.android.contacts.model.AccountTypeManager.java

/**
 * Internal constructor that only performs initial parsing.
 *//*from ww w.ja va  2 s  . c om*/
public AccountTypeManagerImpl(Context context) {
    mContext = context;
    mLocalAccountLocator = DeviceLocalAccountLocator.create(context);
    mTypeProvider = new AccountTypeProvider(context);
    mFallbackAccountType = new FallbackAccountType(context);

    mAccountManager = AccountManager.get(mContext);

    mExecutor = ContactsExecutors.getDefaultThreadPoolExecutor();
    mMainThreadExecutor = ContactsExecutors.newHandlerExecutor(mMainThreadHandler);

    // Request updates when packages or accounts change
    IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
    filter.addDataScheme("package");
    mContext.registerReceiver(mBroadcastReceiver, filter);
    IntentFilter sdFilter = new IntentFilter();
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
    sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
    mContext.registerReceiver(mBroadcastReceiver, sdFilter);

    // Request updates when locale is changed so that the order of each field will
    // be able to be changed on the locale change.
    filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
    mContext.registerReceiver(mBroadcastReceiver, filter);

    mAccountManager.addOnAccountsUpdatedListener(this, mMainThreadHandler, false);

    ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, this);

    if (Flags.getInstance().getBoolean(Experiments.CP2_DEVICE_ACCOUNT_DETECTION_ENABLED)) {
        // Observe changes to RAW_CONTACTS so that we will update the list of "Device" accounts
        // if a new device contact is added.
        mContext.getContentResolver().registerContentObserver(ContactsContract.RawContacts.CONTENT_URI,
                /* notifyDescendents */ true, new ContentObserver(mMainThreadHandler) {
                    @Override
                    public boolean deliverSelfNotifications() {
                        return true;
                    }

                    @Override
                    public void onChange(boolean selfChange) {
                        reloadLocalAccounts();
                    }

                    @Override
                    public void onChange(boolean selfChange, Uri uri) {
                        reloadLocalAccounts();
                    }
                });
    }
    loadAccountTypes();
}

From source file:com.monkey.entonado.MainActivity.java

/**
 * Realiza la conexion al servidor/*  www  .j a v a2  s . c om*/
 * @return mensaje Indica si la conexion fue exitosa
 */
@SuppressLint("NewApi")
public String conectar() {
    intentoConectar = true;
    try {
        System.out.println("Conectado en 4 ");
        canal = new Socket();
        /**
         * Create a client socket with the host,
         * port, and timeout information.
         */
        System.out.println("Conectado en 3");
        canal.bind(null);
        System.out.println("Conectado en 2");
        canal.connect((new InetSocketAddress(ip, 10052)));
        System.out.println("Conectado en 1");
        out = new PrintWriter(canal.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(canal.getInputStream()));

        String info = "";

        AccountManager aManager = AccountManager.get(this);
        Account[] accounts = aManager.getAccountsByType("com.google");

        for (Account account : accounts) {
            String accountId = account.name;
            info += accountId + " : ";
        }

        out.println(INFO_USUARIO + ";" + "U:" + info);

        String mens = in.readLine();

        System.out.println("Estas conectado! " + mens + " : " + canal.getInetAddress());
        mensajeConexion = "Estas conectado!";
        return "Estas Conectado!";
    } catch (SocketException e) {
        System.out.println("No se establecio la conexion");
        mensajeConexion = "No se estableci la conexin: " + e.getMessage();
        return "No se establecio la conexin";
    } catch (Exception e) {
        System.out.println("No se establecio la conexion");
        mensajeConexion = "No se estableci la conexin: " + e.getMessage();
        return "No se establecio la conexin";
    }
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static XiaomiUserProfile queryXiaomiUserProfile(Context context, Account account) {
    XiaomiUserProfile xiaomiUserProfile = null;
    if (account != null) {
        AccountManager am = AccountManager.get(context);
        int count = 0;
        while (count < 2) {
            String authToken = getAuthToken(am, account, Constants.PASSPORT_API_SID);
            ExtendedAuthToken extendedAuthToken = ExtendedAuthToken.parse(authToken);
            if (extendedAuthToken == null) {
                break;
            }/*  ww w .ja v a 2 s  .  c  o m*/
            String serviceToken = extendedAuthToken.authToken;
            String security = extendedAuthToken.security;
            if (serviceToken == null || security == null) {
                break;
            }
            try {
                xiaomiUserProfile = CloudHelper.getXiaomiUserProfile(account.name,
                        am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID), serviceToken, security);
                break;
            } catch (InvalidResponseException e) {
                Log.e(TAG, "invalid response when get user info", e);
            } catch (CipherException e2) {
                Log.e(TAG, "CipherException when get user info", e2);
            } catch (IOException e3) {
                Log.e(TAG, "IOException when get user info", e3);
            } catch (AuthenticationFailureException e4) {
                Log.e(TAG, "auth failure when get user info", e4);
                am.invalidateAuthToken(account.type, authToken);
                count++;
            } catch (AccessDeniedException e5) {
                Log.e(TAG, "access denied when get user info", e5);
            }
        }
    } else {
        Log.w(TAG, "no Xiaomi account, skip to query user profile");
    }
    return xiaomiUserProfile;
}