I am trying to get the authToken
for an account but getting this error:
java.lang.IllegalStateException: calling this from your main thread can lead to deadlock
This is how I'm getting the AuthToken:
public class MyAccount {
private final Account account;
private final AccountManager manager;
private final Context context;
public MyAccount (Context context) {
this.context = context;
final Account[] accounts = AccountManager.get(context).getAccountsByType("com.myapp");
account = accounts.length > 0 ? accounts[0] : null;
manager = AccountManager.get(context);
}
public String getAuthToken() {
@SuppressWarnings("deprecation")
AccountManagerFuture<Bundle> future = manager.getAuthToken(account,"com.myapp", false, null, null);
try {
//GETTING EXCEPTION HERE
Bundle result = future.getResult();
return result != null ? result.getString(KEY_AUTHTOKEN) : null;
} catch (AccountsException e) {
Log.e(TAG, "Auth token lookup failed", e);
return null;
} catch (IOException e) {
Log.e(TAG, "Auth token lookup failed", e);
return null;
}
}
}
I'm calling this from my MainActivity like this:
MyAccount account = new MyAccount(getApplicationContext());
String authtoken = account.getAuthToken());
Question
How can I call MyAccount
to get the authToken and get rid of the exception?
USe an AsyncTask so that this work may be completed in a background thread (doInBackground)
Usage :
new FooTask().execute();