我已经使用各自的方法集成了 google 和 facebook 注册。但是签名成功后,我想打开不同的活动,同样用户可以去各种不同的活动。我使用了操作栏,我可以在其中提供从用户登录的任何一个帐户中退出的选项。当我处于与主要活动不同的活动中时,如何退出用户。我遇到了一个异常,我无法将 apiclient 参考(用于 google)和会话参考(用于 facebook)传递给另一个活动。请帮忙。提前致谢。
15 回答
从谷歌注销:
只需将其添加到您的新活动中,您希望您的 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();
}
接下来您可以在按钮上设置 setOnClickListener:
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);
}
});
}
});
脸书
LoginManager.getInstance().logOut();
对于谷歌
GoogleSignInOptions gso = new GoogleSignInOptions.
Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).
build();
GoogleSignInClient googleSignInClient=GoogleSignIn.getClient(context,gso);
googleSignInClient.signOut();
从脸书注销:
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}
从谷歌注销:
@Override
public void onClick(View view) {
if (view.getId() == R.id.sign_out_button) {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
}
}
}
从 2017 年 11 月 7 日更新 登录和注销事件的最新代码
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
谷歌登出
mGoogleSignInClient.signOut()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
谷歌撤销访问
mGoogleSignInClient.revokeAccess()
.addOnCompleteListener(this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
// [START_EXCLUDE]
updateUI(null);
// [END_EXCLUDE]
}
});
在此处参考 Google 代码
脸书登出
LoginManager.getInstance().logOut();
在此处参考 Facebook 文档
只需添加您的新活动:
@Override
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
接着
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_out_button2:
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
从 Facebook 注销非常简单
只需添加以下代码
LoginManager.getInstance().logOut();
然后,您可以通过进一步添加以下代码将用户重定向到登录活动
LoginManager.getInstance().logOut();
Intent intent = new Intent(CurrentActivity.this, LoginActivity.class);
startActivity(intent);
finish();
所以你 logoutFromFacebook 的最终代码是
public void logoutFromFacebook(){
LoginManager.getInstance().logOut();
Intent intent = new Intent(CurrentActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
现在只需在您的注销按钮事件上调用该方法。
对于谷歌帐户
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
和脸书账户
LoginManager.getInstance().logOut();
首先对于 Facebook 注销:
LoginManager.getInstance().logOut();
如果您尝试从其他活动或片段中注销,这会给您带来错误,例如 Facebook sdk 未初始化。然后首先你必须像这样初始化 facebook sdk:
FacebookSdk.sdkInitialize(your context here);
然后从经理注销。
谷歌注销的次要:
首先,您必须检查谷歌客户端是否已连接,如果已连接,则调用注销代码:
if (mGoogleApiClient.isConnected())
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
这里 mGoogleApiClient 是 GoogleApiClient 的对象。
退出 Google 身份验证的最简单方法:
GoogleSignIn.getClient(getApplicationContext(), GoogleSignInOptions.DEFAULT_SIGN_IN).signOut();
从 Facebook 注销。
public void logoutFromFacebook() {
Session session = Session.getActiveSession();
session.closeAndClearTokenInformation();
// Clear Preferences and other data and go back to login activty
}
从 Google+ 注销。请记住,Google+ 的注销比 Facebook 的注销要复杂一些。单击注销时,您必须管理一个布尔值以跟踪事件(与登录相同)。
public void logoutFromGooglePlus() {
mGooglePlusLogoutClicked = true; // Keep track when you click logout
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
revokeAccess();
} else {
mGoogleApiClient.connect(); // It can send user to onConnected(), call logout again from there
}
}
// revoke access (if needed)
protected void revokeAccess() {
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// Clear data and go to login activity
}
});
}
要回答评论中的问题:
GoogleApiClient
可以在应用程序中多次实例化,并且它仍然采用与第一次初始化相同的实例。所以不用担心如何GoogleApiClient
在活动之间“传递”。它是一个轻量级客户端,旨在在每个活动中初始化为一个新实例。只需建立一个新的GoogleAPiClient
,打电话.connect()
并开始工作。但是,您必须实现它所需的接口,但如果您不打算在那里做任何工作,您可以将这些方法留空。
就mLogoutClicked
布尔值而言,您可以根据需要拥有自己的实现。基本上,这只是一种告诉onConnected()
方法您来注销的方法。(看代码,我们也在调用.connect()
注销。所以它可能会进入onConnected()
并与您的登录代码冲突)。你会在你的onconnected()
public void onConnected(Bundle connectionHint) {
if (mGooglePlusLogoutClicked) {
logoutFromGooglePlus();
mGooglePlusLogoutClicked = false;
}
}
作为对您的实施流程的建议,让一个基类完成所有GoogleApiClient
初始化,并让登录活动和其他活动对其进行扩展。因此它将隐式处理在每个活动中初始化客户端的问题。只需在基本活动中实现 commononConnected()
等onConnectionFailed()
代码,并让登录活动覆盖这些代码以实现登录逻辑。(对于注销活动也是如此。它将覆盖这些并处理注销代码)
这也是在与登录不同的另一项活动中,您应该在哪里拥有登录按钮。
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(fromActivity.getString(R.string.default_web_client_id))
.requestEmail()
.requestProfile()
.build();
// Build a GoogleSignInClient with the options specified by gso.
GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(fromActivity, gso);
mGoogleSignInClient.signOut();
public class LogOutActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener {
GoogleApiClient mGoogleApiClient;
Button btnLogout;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnLogut = (Button) findViewBy(R.id.btnLogout);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
}
Intent intent = new Intent(mContext, LoginActivity.class);
});
}
});
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
给你谷歌。
Button login, signup, signout;
GoogleSignInClient mGoogleSignInClient;
private static final int RC_SIGN_IN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = findViewById(R.id.login);
signup = findViewById(R.id.signup);
signout = findViewById(R.id.signout);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signout.setOnClickListener(v -> mGoogleSignInClient.signOut()
.addOnCompleteListener(this, task -> Log.e("checker", "Sign Out")));
signup.setOnClickListener(v -> {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
});
login.setOnClickListener(v -> {
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
if (account != null) {
String personName = account.getDisplayName();
String personEmail = account.getEmail();
String personId = account.getId();
Uri personPhoto = account.getPhotoUrl();
Log.e("checker", personName);
Log.e("checker", personId);
Log.e("checker", String.valueOf(personPhoto));
Log.e("checker", personEmail);
} else
Log.e("checker", "did not login");
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
if (account != null) {
String personName = account.getDisplayName();
String personEmail = account.getEmail();
String personId = account.getId();
Uri personPhoto = account.getPhotoUrl();
Log.e("checker", personName);
Log.e("checker", personId);
Log.e("checker", String.valueOf(personPhoto));
Log.e("checker", personEmail);
}
else
Log.e("checker", "Failed!");
} catch (ApiException e) {
Log.e("checker", "signInResult:failed code=" + e.getStatusCode());
}
}
这是给脸书的。
LoginManager.getInstance().logOut();
如果您使用的是 Firebase 预构建的 UI,那么
AuthUI.getInstance().signOut(getApplicationContext()).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(), "Sign out successfully", Toast.LENGTH_LONG).show();
signInLauncher.launch(signInIntent);
}
}
});
//FirebaseAuth.getInstance().signOut(); not working in this case
使用它,它将适用于 facebook 和 google:
FirebaseAuth.getInstance().signOut();
GoogleSignIn.getClient(getApplicationContext(),GoogleSignInOptions.DEFAULT_SIGN_IN).signOut();
LoginManager.getInstance().logOut();