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.android.exchange.SyncManager.java

/**
 * Compare our account list (obtained from EmailProvider) with the account list owned by
 * AccountManager.  If there are any orphans (an account in one list without a corresponding
 * account in the other list), delete the orphan, as these must remain in sync.
 *
 * Note that the duplication of account information is caused by the Email application's
 * incomplete integration with AccountManager.
 *
 * This function may not be called from the main/UI thread, because it makes blocking calls
 * into the account manager.//  ww  w.  ja  v a 2  s .com
 *
 * @param context The context in which to operate
 * @param cachedEasAccounts the exchange provider accounts to work from
 * @param accountManagerAccounts The account manager accounts to work from
 * @param blockExternalChanges FOR TESTING ONLY - block backups, security changes, etc.
 * @param resolver the content resolver for making provider updates (injected for testability)
 */
/* package */ static void reconcileAccountsWithAccountManager(Context context, List<Account> cachedEasAccounts,
        android.accounts.Account[] accountManagerAccounts, boolean blockExternalChanges,
        ContentResolver resolver) {
    // First, look through our cached EAS Accounts (from EmailProvider) to make sure there's a
    // corresponding AccountManager account
    boolean accountsDeleted = false;
    for (Account providerAccount : cachedEasAccounts) {
        String providerAccountName = providerAccount.mEmailAddress;
        boolean found = false;
        for (android.accounts.Account accountManagerAccount : accountManagerAccounts) {
            if (accountManagerAccount.name.equalsIgnoreCase(providerAccountName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            if ((providerAccount.mFlags & Account.FLAGS_INCOMPLETE) != 0) {
                log("Account reconciler noticed incomplete account; ignoring");
                continue;
            }
            // This account has been deleted in the AccountManager!
            alwaysLog("Account deleted in AccountManager; deleting from provider: " + providerAccountName);
            // TODO This will orphan downloaded attachments; need to handle this
            resolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI, providerAccount.mId), null, null);
            accountsDeleted = true;
        }
    }
    // Now, look through AccountManager accounts to make sure we have a corresponding cached EAS
    // account from EmailProvider
    for (android.accounts.Account accountManagerAccount : accountManagerAccounts) {
        String accountManagerAccountName = accountManagerAccount.name;
        boolean found = false;
        for (Account cachedEasAccount : cachedEasAccounts) {
            if (cachedEasAccount.mEmailAddress.equalsIgnoreCase(accountManagerAccountName)) {
                found = true;
            }
        }
        if (!found) {
            // This account has been deleted from the EmailProvider database
            alwaysLog("Account deleted from provider; deleting from AccountManager: "
                    + accountManagerAccountName);
            // Delete the account
            AccountManagerFuture<Boolean> blockingResult = AccountManager.get(context)
                    .removeAccount(accountManagerAccount, null, null);
            try {
                // Note: All of the potential errors from removeAccount() are simply logged
                // here, as there is nothing to actually do about them.
                blockingResult.getResult();
            } catch (OperationCanceledException e) {
                Log.w(Email.LOG_TAG, e.toString());
            } catch (AuthenticatorException e) {
                Log.w(Email.LOG_TAG, e.toString());
            } catch (IOException e) {
                Log.w(Email.LOG_TAG, e.toString());
            }
            accountsDeleted = true;
        }
    }
    // If we changed the list of accounts, refresh the backup & security settings
    if (!blockExternalChanges && accountsDeleted) {
        AccountBackupRestore.backupAccounts(context);
        SecurityPolicy.getInstance(context).reducePolicies();
        Email.setNotifyUiAccountsChanged(true);
    }
}

From source file:org.thoughtland.xlocation.ActivityShare.java

@SuppressLint("InflateParams")
public static boolean registerDevice(final ActivityBase context) {
    int userId = Util.getUserId(Process.myUid());
    if (Util.hasProLicense(context) == null
            && !PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingRegistered, false)) {
        // Get accounts
        String email = null;// w w  w .j  a  v a  2  s.  com
        for (Account account : AccountManager.get(context).getAccounts())
            if ("com.google".equals(account.type)) {
                email = account.name;
                break;
            }

        LayoutInflater LayoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = LayoutInflater.inflate(R.layout.register, null);
        final EditText input = (EditText) view.findViewById(R.id.etEmail);
        if (email != null)
            input.setText(email);

        // Build dialog
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle(R.string.msg_register);
        alertDialogBuilder.setIcon(context.getThemed(R.attr.icon_launcher));
        alertDialogBuilder.setView(view);
        alertDialogBuilder.setPositiveButton(context.getString(android.R.string.ok),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String email = input.getText().toString();
                        if (Patterns.EMAIL_ADDRESS.matcher(email).matches())
                            new RegisterTask(context).executeOnExecutor(mExecutor, email);
                    }
                });
        alertDialogBuilder.setNegativeButton(context.getString(android.R.string.cancel),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // Do nothing
                    }
                });

        // Show dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

        return false;
    }
    return true;
}

From source file:com.android.exchange.SyncManager.java

public void run() {
    sStop = false;/*from   w ww .  j a  v a2 s .  co  m*/
    alwaysLog("!!! SyncManager thread running");
    // If we're really debugging, turn on all logging
    if (Eas.DEBUG) {
        Eas.USER_LOG = true;
        Eas.PARSER_LOG = true;
        Eas.FILE_LOG = true;
    }

    // If we need to wait for the debugger, do so
    if (Eas.WAIT_DEBUG) {
        Debug.waitForDebugger();
    }

    // Synchronize here to prevent a shutdown from happening while we initialize our observers
    // and receivers
    synchronized (sSyncLock) {
        if (INSTANCE != null) {
            mResolver = getContentResolver();

            // Set up our observers; we need them to know when to start/stop various syncs based
            // on the insert/delete/update of mailboxes and accounts
            // We also observe synced messages to trigger upsyncs at the appropriate time
            mAccountObserver = new AccountObserver(mHandler);
            mResolver.registerContentObserver(Account.CONTENT_URI, true, mAccountObserver);
            mMailboxObserver = new MailboxObserver(mHandler);
            mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
            mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
            mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);
            mMessageObserver = new MessageObserver(mHandler);
            mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver);
            mSyncStatusObserver = new EasSyncStatusObserver();
            mStatusChangeListener = ContentResolver
                    .addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver);

            // Set up our observer for AccountManager
            mAccountsUpdatedListener = new EasAccountsUpdatedListener();
            AccountManager.get(getApplication()).addOnAccountsUpdatedListener(mAccountsUpdatedListener,
                    mHandler, true);

            // Set up receivers for connectivity and background data setting
            mConnectivityReceiver = new ConnectivityReceiver();
            registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

            mBackgroundDataSettingReceiver = new ConnectivityReceiver();
            registerReceiver(mBackgroundDataSettingReceiver,
                    new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
            // Save away the current background data setting; we'll keep track of it with the
            // receiver we just registered
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mBackgroundData = cm.getBackgroundDataSetting();

            // See if any settings have changed while we weren't running...
            checkPIMSyncSettings();
        }
    }

    try {
        // Loop indefinitely until we're shut down
        while (!sStop) {
            runAwake(SYNC_MANAGER_ID);
            waitForConnectivity();
            mNextWaitReason = "Heartbeat";
            long nextWait = checkMailboxes();
            try {
                synchronized (this) {
                    if (!mKicked) {
                        if (nextWait < 0) {
                            log("Negative wait? Setting to 1s");
                            nextWait = 1 * SECONDS;
                        }
                        if (nextWait > 10 * SECONDS) {
                            log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason);
                            runAsleep(SYNC_MANAGER_ID, nextWait + (3 * SECONDS));
                        }
                        wait(nextWait);
                    }
                }
            } catch (InterruptedException e) {
                // Needs to be caught, but causes no problem
                log("SyncManager interrupted");
            } finally {
                synchronized (this) {
                    if (mKicked) {
                        //log("Wait deferred due to kick");
                        mKicked = false;
                    }
                }
            }
        }
        log("Shutdown requested");
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in SyncManager", e);
        throw e;
    } finally {
        shutdown();
    }
}

From source file:com.mwebster.exchange.SyncManager.java

public void run() {
    mStop = false;/* ww w. j a v a  2s .co m*/

    // If we're really debugging, turn on all logging
    if (Eas.DEBUG) {
        Eas.USER_LOG = true;
        Eas.PARSER_LOG = true;
        Eas.FILE_LOG = true;
    }

    // If we need to wait for the debugger, do so
    if (Eas.WAIT_DEBUG) {
        Debug.waitForDebugger();
    }

    // Set up our observers; we need them to know when to start/stop various syncs based
    // on the insert/delete/update of mailboxes and accounts
    // We also observe synced messages to trigger upsyncs at the appropriate time
    mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
    mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);
    mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver);
    ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver);
    mAccountsUpdatedListener = new EasAccountsUpdatedListener();
    // TODO Find and fix root cause of duplication
    try {
        AccountManager.get(getApplication()).addOnAccountsUpdatedListener(mAccountsUpdatedListener, mHandler,
                true);
    } catch (IllegalStateException e1) {
        // This exception is more of a warning; we shouldn't be in the state in which we
        // already have a listener.
    }

    // Set up receivers for ConnectivityManager
    mConnectivityReceiver = new ConnectivityReceiver();
    registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    mBackgroundDataSettingReceiver = new ConnectivityReceiver();
    registerReceiver(mBackgroundDataSettingReceiver,
            new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
    // Save away background data setting; we'll keep track of it with the receiver
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mBackgroundData = cm.getBackgroundDataSetting();

    // See if any settings have changed while we weren't running...
    checkPIMSyncSettings();

    try {
        while (!mStop) {
            runAwake(SYNC_MANAGER_ID);
            waitForConnectivity();
            mNextWaitReason = "Heartbeat";
            long nextWait = checkMailboxes();
            try {
                synchronized (this) {
                    if (!mKicked) {
                        if (nextWait < 0) {
                            log("Negative wait? Setting to 1s");
                            nextWait = 1 * SECONDS;
                        }
                        if (nextWait > 10 * SECONDS) {
                            log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason);
                            runAsleep(SYNC_MANAGER_ID, nextWait + (3 * SECONDS));
                        }
                        wait(nextWait);
                    }
                }
            } catch (InterruptedException e) {
                // Needs to be caught, but causes no problem
            } finally {
                synchronized (this) {
                    if (mKicked) {
                        //log("Wait deferred due to kick");
                        mKicked = false;
                    }
                }
            }
        }
        log("Shutdown requested");
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in SyncManager", e);
        throw e;
    } finally {
        log("Finishing SyncManager");
        // Lots of cleanup here
        // Stop our running syncs
        stopServiceThreads();

        // Stop receivers and content observers
        if (mConnectivityReceiver != null) {
            unregisterReceiver(mConnectivityReceiver);
        }
        if (mBackgroundDataSettingReceiver != null) {
            unregisterReceiver(mBackgroundDataSettingReceiver);
        }

        if (INSTANCE != null) {
            ContentResolver resolver = getContentResolver();
            resolver.unregisterContentObserver(mAccountObserver);
            resolver.unregisterContentObserver(mMailboxObserver);
            resolver.unregisterContentObserver(mSyncedMessageObserver);
            resolver.unregisterContentObserver(mMessageObserver);
            unregisterCalendarObservers();
        }
        // Don't leak the Intent associated with this listener
        if (mAccountsUpdatedListener != null) {
            AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener);
            mAccountsUpdatedListener = null;
        }

        // Clear pending alarms and associated Intents
        clearAlarms();

        // Release our wake lock, if we have one
        synchronized (mWakeLocks) {
            if (mWakeLock != null) {
                mWakeLock.release();
                mWakeLock = null;
            }
        }

        log("Goodbye");
    }

    if (!mStop) {
        // If this wasn't intentional, try to restart the service
        throw new RuntimeException("EAS SyncManager crash; please restart me...");
    }
}

From source file:com.android.exchange.SyncManager.java

private void shutdown() {
    synchronized (sSyncLock) {
        // If INSTANCE is null, we've already been shut down
        if (INSTANCE != null) {
            log("SyncManager shutting down...");

            // Stop our running syncs
            stopServiceThreads();/*w  ww.  j  a  v  a  2s  . c om*/

            // Stop receivers
            if (mConnectivityReceiver != null) {
                unregisterReceiver(mConnectivityReceiver);
            }
            if (mBackgroundDataSettingReceiver != null) {
                unregisterReceiver(mBackgroundDataSettingReceiver);
            }

            // Unregister observers
            ContentResolver resolver = getContentResolver();
            if (mSyncedMessageObserver != null) {
                resolver.unregisterContentObserver(mSyncedMessageObserver);
                mSyncedMessageObserver = null;
            }
            if (mMessageObserver != null) {
                resolver.unregisterContentObserver(mMessageObserver);
                mMessageObserver = null;
            }
            if (mAccountObserver != null) {
                resolver.unregisterContentObserver(mAccountObserver);
                mAccountObserver = null;
            }
            if (mMailboxObserver != null) {
                resolver.unregisterContentObserver(mMailboxObserver);
                mMailboxObserver = null;
            }
            unregisterCalendarObservers();

            // Remove account listener (registered with AccountManager)
            if (mAccountsUpdatedListener != null) {
                AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener);
                mAccountsUpdatedListener = null;
            }

            // Remove the sync status change listener (and null out the observer)
            if (mStatusChangeListener != null) {
                ContentResolver.removeStatusChangeListener(mStatusChangeListener);
                mStatusChangeListener = null;
                mSyncStatusObserver = null;
            }

            // Clear pending alarms and associated Intents
            clearAlarms();

            // Release our wake lock, if we have one
            synchronized (mWakeLocks) {
                if (mWakeLock != null) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }

            INSTANCE = null;
            sServiceThread = null;
            sStop = false;
            log("Goodbye");
        }
    }
}

From source file:com.android.launcher2.Launcher.java

private boolean skipCustomClingIfNoAccounts() {
    Cling cling = (Cling) findViewById(R.id.workspace_cling);
    boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
    if (customCling) {
        AccountManager am = AccountManager.get(this);
        Account[] accounts = am.getAccountsByType("com.google");
        return accounts.length == 0;
    }/*  w ww .  ja  va2  s  . com*/
    return false;
}

From source file:com.android.soma.Launcher.java

private boolean skipCustomClingIfNoAccounts() {
    Cling cling = (Cling) findViewById(R.id.workspace_cling);
    boolean customCling = cling.getDrawIdentifier().equals("workspace_custom");
    if (customCling) {
        AccountManager am = AccountManager.get(this);
        if (am == null)
            return false;
        Account[] accounts = am.getAccountsByType("com.google");
        return accounts.length == 0;
    }//from   w  ww  .java2s  .  co m
    return false;
}