33

我已经开始使用Google+ APIfor android,并按照本教程创建了一个登录应用程序:

https://developers.google.com/+/mobile/android/sign-in

现在,问题是我想从另一个创建退出按钮Activity,而我尝试做的并没有真正奏效..

我的 GPlusLogin 代码(Google+ 登录活动):

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import com.google.android.gms.common.*;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.plus.PlusClient;

public class GPlusLogin extends Activity implements ConnectionCallbacks, OnConnectionFailedListener{

    private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
    private static final String TAG = "GPlusLogin";

    private ProgressDialog mConnectionProgressDialog;
    private PlusClient mPlusClient;
    private ConnectionResult mConnectionResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gplus_layout);
        mPlusClient = new PlusClient.Builder(this, this, this).setVisibleActivities("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
        Bundle extras = getIntent().getExtras();
        mConnectionProgressDialog = new ProgressDialog(this);
        mConnectionProgressDialog.setMessage("Signing in...");

        if(extras!=null){
            if(extras.getString("signout")!=null){
                if (mPlusClient.isConnected()) {
                    mPlusClient.clearDefaultAccount();
                    mPlusClient.disconnect();
                    mPlusClient.connect();
                    finish();
                    startActivity(getIntent());
                }
            }
        }else{

            findViewById(R.id.sign_in_button).setOnClickListener(new OnClickListener() {

                public void onClick(View view) {
                    // TODO Auto-generated method stub
                    if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
                        if (mConnectionResult == null) {
                            mConnectionProgressDialog.show();
                        } else {
                            try {
                                mConnectionResult.startResolutionForResult(GPlusLogin.this, REQUEST_CODE_RESOLVE_ERR);
                            } catch (SendIntentException e) {
                                // Try connecting again.
                                mConnectionResult = null;
                                mPlusClient.connect();
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        mPlusClient.connect();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mPlusClient.disconnect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // TODO Auto-generated method stub
        if (mConnectionProgressDialog.isShowing()) {
            // The user clicked the sign-in button already. Start to resolve
            // connection errors. Wait until onConnected() to dismiss the
            // connection dialog.
            if (result.hasResolution()) {
                try {
                    result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
                } catch (SendIntentException e) {
                    mPlusClient.connect();
                }
            }
        }

        mConnectionResult = result;
    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
        if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
            mConnectionResult = null;
            mPlusClient.connect();
        }
    }

    @Override
    public void onConnected() {
        // TODO Auto-generated method stub
        mConnectionProgressDialog.dismiss();
        Intent main = new Intent(GPlusLogin.this, MainActivity.class);
        main.putExtra("result", true);
        startActivity(main);
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        Log.d(TAG, "disconnected");
    }

}

我的断开连接代码MainActivity

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Bundle extras = getIntent().getExtras();
        if(extras==null){
            Intent intent = new Intent(this, GPlusLogin.class);
            startActivity(intent);
        }
        TextView text1 = (TextView) findViewById(R.id.text1);
        text1.setText("You Are Connected :D");

        Button SignOut = (Button) findViewById(R.id.sign_out_gplus);
        SignOut.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(MainActivity.this, GPlusLogin.class);
                intent.putExtra("signout", true);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


}
4

9 回答 9

29

只需将其添加到您的新活动中,您希望您的 google+ 注销按钮在那里:

@Override
protected void onStart() {
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    mGoogleApiClient.connect();
    super.onStart();
}

接下来:

 signout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
                  new ResultCallback<Status>() {
                      @Override
                      public void onResult(Status status) {
                          // ...
                          Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_SHORT).show();
                          Intent i=new Intent(getApplicationContext(),MainActivity.class);
                          startActivity(i);
                      }
                  });
      }
  });
于 2016-08-16T14:18:25.827 回答
18

嘿,我自己解决了这个问题,像魅力一样工作

问题是什么:谷歌加登录在一项活动中,但需要从另一项活动中注销

解决方案:

我的 Google-plus 注销活动是这样的:

public class MainActivity extends Activity implements OnClickListener,
    ConnectionCallbacks, OnConnectionFailedListener,
    ResultCallback<People.LoadPeopleResult> {

   GoogleApiClient mGoogleApiClient;
   boolean mSignInClicked;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).addApi(Plus.API)
            .addScope(Plus.SCOPE_PLUS_LOGIN).build();

     //copy this code on "Logout" Onclick
  logout.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            // updateUI(false);
            System.err.println("LOG OUT ^^^^^^^^^^^^^^^^^^^^ SUCESS");
        } 

        }
    });

}
@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    mSignInClicked = false;

    // updateUI(true);
    Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(
            this);
}

@Override
public void onConnectionSuspended(int arg0) {
    // TODO Auto-generated method stub
    mGoogleApiClient.connect();
    // updateUI(false);
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub

}

protected void onStart() {
    super.onStart();
    mGoogleApiClient.connect();
}

protected void onStop() {
    super.onStop();
    if (mGoogleApiClient.isConnected()) {
        mGoogleApiClient.disconnect();
    }
}

@Override
public void onResult(LoadPeopleResult arg0) {
    // TODO Auto-generated method stub

}

解决方案说明:

对于单个包 google plus API 将生成一个令牌和会话。只是在这里只需在注销页面中再创建一个会话。您现在可以轻松地从会话中注销

我已经尝试了很多关于这个问题,从当前会话注销,试试这个。它肯定会工作。有任何疑问让我知道

于 2015-03-27T11:03:07.827 回答
6

创建基类并继承连接/断开连接方法可能会更容易。Photohunt,我们的完整样本,详细记录了这个设计。

文档 代码

于 2013-03-14T17:39:48.733 回答
2

经过一个多星期的努力寻找答案。我这样做了,登录后将 sharedpreferences 中的布尔 isSignedIn 保存为 true。

private SharedPreferences.Editor editor;
private SharedPreferences prefs;

editor = getSharedPreferences(getString(R.string.userDetails), MODE_PRIVATE).edit();
editor.putBoolean(getString(R.string.isSignedIn), true);
editor.apply();`

现在,从用户单击注销时的任何活动中,将布尔值更改为 false。

在您的登录活动中googleApiClient构建。在其 onStart 方法中。检查是否isSignedIn为假。

@Override
public void onStart() {
super.onStart();
if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
    signOut();
    }     
}

做同样的事情onConnected

@Override
public void onConnected(Bundle connectionHint) {
    if (mGoogleApiClient.isConnected()) {
        Log.i(TAG, "onConnected: " + "yes it is connected");
        if (!prefs.getBoolean(getString(R.string.isSignedIn), false)) {
            signOut();
        }
    }
}

这将注销并撤销访问权限。

public void signOut() {
    if (mGoogleApiClient != null) {
        Log.e(TAG, "signOut: " + mGoogleApiClient + mGoogleApiClient.isConnected());
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
        if (mGoogleApiClient.isConnected()) {
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            // ...
                            Log.i(TAG, "onResult: " + mGoogleApiClient);
                        }
                    });
         Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
                    new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status status) {
                            Log.i(TAG, "onResult: Revoke Access status:" + status.getStatus());
                        }
                    });
        }
    }
}
于 2017-10-04T09:04:03.947 回答
2

您可以从应用程序的任何位置获取 FirebaseAuth 的实例,因为 FirebaseAuth 是一个单例类。

 mAuth = FirebaseAuth.getInstance();
 mAuth.signOut();
于 2017-12-01T12:06:01.443 回答
1

乔纳森是正确的,基类或片段会让你的生活更轻松。也就是说,这里的代码可以工作 - 问题是您正在检查 PlusClient 是否已连接onCreate()- 但直到onStart(). 您可能需要检查onConnected()方法中的意图,并在那里执行签名。

于 2013-03-19T22:39:07.870 回答
1

从另一个活动中单击注销后,请尝试发送带有额外信息的意图以指示单击了注销按钮。然后在登录活动

if (Intent.Extras != null && Intent.Extras.ContainsKey("LogoutAction")) {
    _logoutRequest = Intent.Extras.GetBoolean("LogoutAction");
}
if (_logoutRequest) {
    await PlusClass.AccountApi.RevokeAccessAndDisconnect(_apiClient);
    _apiClient.Disconnect();
    _apiClient.Connect ();
    _logoutRequest = false;
}

其他活动

var intent = new Intent(this.Activity,typeof(LoginActivity));
intent.PutExtra("LogoutAction",true);
于 2016-04-27T07:38:51.490 回答
1

sommesh的答案是完美的,但是对于更少的代码,您可以像这样使用“公共静态方法”:

public static GoogleApiClient mGoogleApiClient;
...
...
public static void signOutFromGoogle() {
    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    //...
                }
            });
}

在您的其他活动上调用它:

Your_Google_Activity.mGoogleApiClient.connect();
btnSignOut.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {            
        Your_Google_Activity.signOutFromGoogle();
    }
});
于 2017-08-27T17:09:10.823 回答
1

这是我的解决方案。我做了一个Utils 单例类。在 myLoginActivity中,我有一个GoogleSignInClient对象。所以就在DashboardActivity登录后开始之前,我googleSignInClient通过调用来保存对象的实例Utils.getInstance().setGoogleSignInClient(googleSignInClient)。现在在其他任何地方,如果我想注销,我已经Utils准备好这个方法:

public void signOut() {
    googleSignInClient.signOut();
    FirebaseAuth.getInstance().signOut();
}

所以现在,我可以从任何其他活动中做到这一点:

else if (id == R.id.action_logout) {
    Utils.getInstance().signOut();
    Intent intent = new Intent(this, LoginActivity.class);
    startActivity(intent);
}

是的,您需要从两者中注销,否则,您下次点击登录按钮时可能看不到帐户选择器。

于 2019-06-06T06:19:03.770 回答