Skip to content Skip to sidebar Skip to footer

Custom Account Authenticator. Cleanup After Account Is Removed From Device

Is there a way to get some kind of notification/broadcast/etc. when a custom account is removed from 'Accounts & sync settings'? The application I have can facilitate multiple

Solution 1:

You have two options:

  1. You can use the addOnAccountsUpdatedListener method of AccountManager to add a listener in the onCreate method of an Activity or Service -- make sure you remove the listener in your onDestroy method (i.e. do NOT use this in an endlessly running service) or the Context used to retrieve the AccountManager will never be garbage collected

  2. The AccountsService will broadcast an intent with the action AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION every time an account is added, removed or changed which you can add a receiver for.

Solution 2:

I didn't see a lot of examples on how people implement account cleanup, so I thought I would post my solution (really a variation of the accepted answer).

publicclassAccountAuthenticatorServiceextendsService {
    private AccountManager _accountManager;
    private Account[] _currentAccounts;
    privateOnAccountsUpdateListener_accountsUpdateListener=newOnAccountsUpdateListener() {
        @OverridepublicvoidonAccountsUpdated(Account[] accounts) {

            // NOTE: this is every account on the device (you may want to filter by type)if(_currentAccounts == null){
                _currentAccounts = accounts;
                return;
            }

            for(Account currentAccount : _currentAccounts) {
                booleanaccountExists=false;
                for (Account account : accounts) {
                    if(account.equals(currentAccount)){
                        accountExists = true;
                        break;
                    }
                }

                if(!accountExists){
                    // Take actions to clean up.  Maybe send intent on Local Broadcast reciever
                }
            }
        }
    };

    publicAccountAuthenticatorService() {

    }

    @OverridepublicvoidonCreate() {
        super.onCreate();
        _accountManager = AccountManager.get(this);

        // set to true so we get the current list of accounts right away.
        _accountManager.addOnAccountsUpdatedListener(_accountsUpdateListener, newHandler(), true);
    }

    @OverridepublicvoidonDestroy() {
        super.onDestroy();
       _accountManager.removeOnAccountsUpdatedListener(_accountsUpdateListener);
    }

    @Overridepublic IBinder onBind(Intent intent) {
        AccountAuthenticatorauthenticator=newAccountAuthenticator(this);
        return authenticator.getIBinder();
    }
}

Post a Comment for "Custom Account Authenticator. Cleanup After Account Is Removed From Device"