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:
You can use the
addOnAccountsUpdatedListenermethod ofAccountManagerto add a listener in theonCreatemethod of anActivityorService-- make sure you remove the listener in youronDestroymethod (i.e. do NOT use this in an endlessly running service) or theContextused to retrieve theAccountManagerwill never be garbage collectedThe
AccountsServicewill broadcast an intent with the actionAccountManager.LOGIN_ACCOUNTS_CHANGED_ACTIONevery 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"