第一次一切正常,如果您第二次启动,则会看到此错误:
FATAL EXCEPTION: main
Process: ro.vrt.videoplayerstreaming, PID: 23662
java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0
at com.google.android.gms.common.internal.zzx.zza(Unknown Source)
at com.google.android.gms.common.api.internal.zzw.zza(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.zza(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.zze(Unknown Source)
at com.google.android.gms.common.api.GoogleApiClient$Builder.build(Unknown Source)
at ro.vrt.videoplayerstreaming.Login.onCreateView(Login.java:75)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5849)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:763)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:653)
这是我的代码:
public class Login extends Fragment implements
GoogleApiClient.OnConnectionFailedListener,
View.OnClickListener {
private static final String TAG = "SignInActivity";
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private TextView mStatusTextView;
private ProgressDialog mProgressDialog;
private static String url;
private static View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null)
parent.removeView(view);
}
try {
view = inflater.inflate(R.layout.activity_login, container, false);
// Views
mStatusTextView = (TextView) view.findViewById(R.id.status);
// Button listeners
view.findViewById(R.id.sign_in_button).setOnClickListener(this);
view.findViewById(R.id.sign_out_button).setOnClickListener(this);
view.findViewById(R.id.disconnect_button).setOnClickListener(this);
// [START configure_signin]
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// [END configure_signin]
// [START build_client]
// Build a GoogleApiClient with access to the Google Sign-In API and the
// options specified by gso.
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity()/* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
// [END build_client]
// [START customize_button]
// Customize sign-in button. The sign-in button can be displayed in
// multiple sizes and color schemes. It can also be contextually
// rendered based on the requested scopes. For example. a red button may
// be displayed when Google+ scopes are requested, but a white button
// may be displayed when only basic profile is requested. Try adding the
// Scopes.PLUS_LOGIN scope to the GoogleSignInOptions to see the
// difference.
SignInButton signInButton = (SignInButton) view.findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
signInButton.setScopes(gso.getScopeArray());
// [END customize_button]
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
super.onCreate(savedInstanceState);
return view;
}
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
//adaugat de mine sa porneacsa singur cererea de logare
signIn();
//fin
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
// [START onActivityResult]
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
// [END onActivityResult]
// [START handleSignInResult]
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName() + " Your token " + acct.getId()));
url = "http://grupovrt.ddns.net:81/index.php?token="+acct.getId();
updateUI(true);
} else {
// Signed out, show unauthenticated UI.
updateUI(false);
}
}
// [END handleSignInResult]
// [START signIn]
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
// [END signIn]
// [START signOut]
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END signOut]
// [START revokeAccess]
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END revokeAccess]
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setIndeterminate(true);
}
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
private void updateUI(boolean signedIn) {
if (signedIn) {
getView().findViewById(R.id.sign_in_button).setVisibility(View.GONE);
getView().findViewById(R.id.sign_out_and_disconnect).setVisibility(View.VISIBLE);
} else {
mStatusTextView.setText(R.string.signed_out);
getView().findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
getView().findViewById(R.id.sign_out_and_disconnect).setVisibility(View.GONE);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
signIn();
break;
case R.id.sign_out_button:
signOut();
break;
case R.id.disconnect_button:
revokeAccess();
break;
}
}
}
据我所知,问题出在以下几个方面:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity()/* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
我尝试过显式传递0
:
.enableAutoManage(getActivity() /* FragmentActivity */, 0, this /* OnConnectionFailedListener */)
但仍然没有效果。
我错过了什么?
答案 0 :(得分:121)
您应该使用stopAutoManage()
的{{1}}方法拨打onPause()
:
Fragment
答案 1 :(得分:33)
您应该在onPause()
的{{1}}方法中致电stopAutoManage()
,如下所示:
Fragment
答案 2 :(得分:19)
避免进一步的问题
@Override
public void onStop() {
super.onStop();
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
mGoogleApiClient.stopAutoManage((Activity) context);
mGoogleApiClient.disconnect();
}
}
答案 3 :(得分:10)
当我在属于同一Fragment
的两个不同Activity
中放置登录按钮时,我遇到了类似的问题。
我通过为每个自动管理的GoogleApiClient
分配不同的ID来解决此问题。
例如,在Fragment
1中,在创建我的GoogleApiClient
对象时,我指定为0 作为ID:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), 0, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
在Fragment
2中,在创建我的GoogleApiClient
对象时,我指定了1 作为ID:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.enableAutoManage(getActivity(), 1, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
答案 4 :(得分:5)
official doc for enableAutoManage说:
在任何给定时间,每个ID只允许一个自动管理的客户端。要重用id,必须先在前一个客户端上调用stopAutoManage(FragmentActivity)。
您的代码使用的是enableAutoManage版本而没有clientId参数,因此它默认为0.下面我解释为什么您将为clientId 0提供多个自动管理客户端,这就是上述文档警告的内容。
将您的登录片段附加到FragmentActivity后,它会告诉该活动开始管理GoogleApiClient的新实例。但是,如果FragmentActivity已经在管理另一个GoogleApiClient实例呢?那是你收到错误的时候。
有一些可能的情况可能导致多个GoogleApiClients-per-FragmentActivity情况。
也许您在FragmentTransaction中添加Login Fragment并调用addToBackStack。然后用户点击回来,然后稍后以某种方式重新附加登录片段。在这种情况下,重要的Login Activity方法调用是onCreateView - &gt; onDestroyView - &gt; onCreateView如下所示:
这是有问题的,因为第二次调用Login.onCreateView会尝试让FragmentActivity管理第二个GoogleApiClient。
如果我是你,我会认真考虑在活动中创建GoogleApiClient而不是任何片段。那么你可以在Activity中完成需要GoogleApiClient的工作,或者在从Activity中获取GoogleApiClient之后继续在Login Fragment中执行此操作:
private GoogleApiClient googleApiClient;
@Override
void onAttach(Activity activity) {
super.onAttach(activity);
googleApiClient = activity.getGoogleApiClient();
}
@Override
void onDetach() {
super.onDetach();
googleApiClient = null;
}
答案 5 :(得分:1)
我建议您在mGoogleApiClient
而不是onCreate()
中初始化onCreateView()
。
作为pointed out by @vlazzle,onCreateView()
可以在单个Activity
的生命周期内被多次调用。
答案 6 :(得分:0)
您应该在片段的stopAutoManage()
方法中调用onDestroy()
,如下所示:
@Override
public void onDestroy() {
super.onDestroy();
mGoogleApiClient.stopAutoManage(getActivity());
mGoogleApiClient.disconnect();
}
答案 7 :(得分:0)
这对我来说可以避免使用Kotlin导致崩溃的问题
private lateinit var googleApiClient: GoogleApiClient
然后验证该变量是否已初始化
if(!::googleApiClient.isInitialized) {
googleApiClient = GoogleApiClient.Builder(context)
.enableAutoManage(activity, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, options)
.build()
}
答案 8 :(得分:-1)
如果您在“活动”中多次使用Login
片段,则选中的答案将不起作用,因为在短时间内顺序添加片段会导致相同的崩溃。 Android有时会混合在Activity中添加的片段的生命周期。
因此,我建议您在单独的抽象活动中为mGoogleApiClient
做一名工作人员,并让所有添加Login
片段的活动都扩展此活动。
通过在下面创建此抽象活动,我设法摆脱了崩溃,只需将其复制粘贴到您的项目中即可:
abstract class LoginableActivity : BaseActivity() {
lateinit var googleApiClient: GoogleApiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.fcm))
.requestEmail()
.build()
googleApiClient = GoogleApiClient.Builder(this)
.enableAutoManage(this, 1, null)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
}
override fun onStart() {
super.onStart()
if (!googleApiClient.isConnected && !googleApiClient.isConnecting) {
googleApiClient.connect()
}
}
override fun onStop() {
super.onStop()
if (googleApiClient.isConnected) {
googleApiClient.stopAutoManage(this)
googleApiClient.disconnect()
}
}
}
将googleApiClient
移至LoginableActivity
之后,您可以像这样从googleApiClient
片段访问Login
(让我们用Java来做):
final Activity = getActivity();
if (activity instanceof LoginableActivity) {
final GoogleApiClient googleApiClient = ((LoginableActivity) activity).googleApiClient;
}
答案 9 :(得分:-2)
尝试使用您活动中的mGoogleApiClient
。
如果您已在活动中声明GoogleApiClient
,则无法在您的片段上重新声明。相反,从片段
mGoogleApiClientInFragment = ((Youractivityclass)getActivity()).mGoogleApiClient;
将YouractivityClass
替换为您的片段活动,并确保将您的活动中的mGoogleApiClient
字段设置为公开