gpt4 book ai didi

android - 尝试从帐户获取 AuthToken 时如何摆脱 java.lang.IllegalStateException

转载 作者:太空宇宙 更新时间:2023-11-03 13:25:38 25 4
gpt4 key购买 nike

我正在尝试获取帐户的 authToken 但出现此错误:

java.lang.IllegalStateException: calling this from your main thread can lead to deadlock

这就是我获取 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;
}
}
}

我是这样从我的 MainActivity 中调用它的:

 MyAccount account = new MyAccount(getApplicationContext());
String authtoken = account.getAuthToken());

问题

如何调用 MyAccount 获取 authToken 并消除异常?

最佳答案

使用AsyncTask这样这个工作就可以在后台线程(doInBackground)中完成

private class FooTask extends AsyncTask<Void, Void, String>{
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
@Override
protected String doInBackground(Void... params) {
MyAccount account = new MyAccount(getApplicationContext());
String authtoken = account.getAuthToken());
return authtoken;
}

/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@Override
protected void onPostExecute(String token) {
if (token != null){
//use token here
}
}
}

用法:new FooTask().execute();

关于android - 尝试从帐户获取 AuthToken 时如何摆脱 java.lang.IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20749044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com