在我的android应用程序中,我正试图从GoogleAuthUtil获取AccessToken,如下所示:
accessToken=GoogleAuthUtil.getToken(this,mPlusClient.getAccountName(),"oauth2:"+SCOPES);
但在这一行,我得到的错误如下:
E/GoogleAuthUtil(4696):从主线程调用它可能会导致死锁和/或ANRE/GoogleAuthUtil(4696):java.lang.IllegalStateException:从主线程调用它可能导致死锁E/GoogleAuthUtil(4696):在com.google.android.gms.auth.GoogleAuthUtil.b(未知来源)E/GoogleAuthUtil(4696):在com.google.android.gms.auth.GoogleAuthUtil.getToken(未知来源)E/GoogleAuthUtil(4696):在com.google.android.gms.auth.GoogleAuthUtil.getToken(未知来源)
这个问题有什么解决办法吗?任何帮助都将不胜感激。
用这样的AsyncTask试试:
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String token = null;
try {
token = GoogleAuthUtil.getToken(
MainActivity.this,
mGoogleApiClient.getAccountName(),
"oauth2:" + SCOPES);
} catch (IOException transientEx) {
// Network or server error, try later
Log.e(TAG, transientEx.toString());
} catch (UserRecoverableAuthException e) {
// Recover (with e.getIntent())
Log.e(TAG, e.toString());
Intent recover = e.getIntent();
startActivityForResult(recover, REQUEST_CODE_TOKEN_AUTH);
} catch (GoogleAuthException authEx) {
// The call is not ever expected to succeed
// assuming you have already verified that
// Google Play services is installed.
Log.e(TAG, authEx.toString());
}
return token;
}
@Override
protected void onPostExecute(String token) {
Log.i(TAG, "Access token retrieved:" + token);
}
};
task.execute();
SCOPES
是OAuth 2.0作用域字符串的以空格分隔的列表。例如,SCOPES
可以定义为:
public static final String SCOPES = "https://www.googleapis.com/auth/plus.login "
+ "https://www.googleapis.com/auth/drive.file";
这些代表您的应用程序向用户请求的权限。此示例中请求的范围记录在此处:
- https://developers.google.com/+/api/oauth
- https://developers.google.com/drive/android/files
为您的互联网代码使用单独的线程。错误表明更多耗时的进程正在应用程序中运行,这里是互联网。因此,请使用单独的线程或异步任务。
查看此链接NetworkOnMainThreadException
希望它能帮助你。
E/GoogleAuthUtil(4696):java.lang.IollegalStateException:调用从您的主线程可以导致死锁
听起来你需要在一个单独的线程上这样做,你尝试过吗?
在这里你可以找到关于Android线程的信息。
Thread CrearEventoHilo = new Thread(){
public void run(){
//do something that retrun "Calling this from your main thread can lead to deadlock"
}
};
CrearEventoHilo.start();
CrearEventoHilo.interrupt()
public class Foo {
MyThread mTh;
void cantBeBothered() {
mTh = new MyThread( /*...*/ );
mTh.run();
mTh.start();
}
void imFinishedNowWaitingForThread() {
mTh.join();
}
void imOutKillingOffPendingThread() {
mTh.interrupt();
}
// .....
private class MyThread extends Thread {
// ...;
MyThread( /*...*/) {
// this... = ...;
}
public void run() {
doSomething( /*this...*/ );
}
}
}