Created
June 7, 2014 18:38
-
-
Save alorma/59ddcddbd9986244db4f to your computer and use it in GitHub Desktop.
Account credential helper that add account on Android AccountManager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package app.picaboo.android.security; | |
import android.accounts.Account; | |
import android.accounts.AccountManager; | |
import android.content.Context; | |
import java.util.UUID; | |
import app.picaboo.android.BuildConfig; | |
/** | |
* Created by Bernat on 07/06/2014. | |
*/ | |
public class CredentialsHelper { | |
private static final String TYPE = BuildConfig.ACCOUNT_TYPE; | |
private final AccountManager accountManager; | |
public CredentialsHelper(Context context) { | |
accountManager = AccountManager.get(context); | |
} | |
public boolean saveUser(String user, String password) { | |
Account account = new Account(user, TYPE); | |
return accountManager.addAccountExplicitly(account, password, null); | |
} | |
private void savePass(String password) { | |
if (getAccount() != null) { | |
accountManager.setPassword(getAccount(), getRandomPassword()); | |
} | |
} | |
public String getUser() { | |
if (getAccount() != null) { | |
return getAccount().name; | |
} | |
return ""; | |
} | |
public String getPassword() { | |
if (getAccount() == null) { | |
return getRandomPassword(); | |
} else if (accountManager.getPassword(getAccount()) == null) { | |
accountManager.setPassword(getAccount(), getRandomPassword()); | |
} | |
return accountManager.getPassword(getAccount()); | |
} | |
private String getRandomPassword() { | |
return UUID.randomUUID().toString(); | |
} | |
public void clear() { | |
if (getAccount() != null) { | |
accountManager.removeAccount(getAccount(), null, null); | |
} | |
} | |
private Account getAccount() { | |
Account[] accounts = accountManager.getAccountsByType(TYPE); | |
if (accounts != null && accounts.length > 0) { | |
return accounts[0]; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment