20

Tôi đã xem xét một số câu hỏi về lưu lượng truy cập liên quan đến đăng nhập và đăng xuất khỏi google plus. Và hầu hết trong số họ đã lỗi thời. Tôi không thể đạt được những gì tôi thực sự muốn.Google đăng nhập và đăng xuất bằng Android bằng cách sử dụng g-plus API mới nhất

Khi tôi đã đăng xuất, lần tiếp theo tôi đăng nhập, tôi muốn người dùng chọn tài khoản google có sẵn để đăng nhập lại.

Tôi đang sử dụng nút đăng nhập và đăng xuất tùy chỉnh. Và để đăng xuất, tôi có hai trường hợp,

  1. đăng xuất ngay trước khi đăng nhập nếu bất kỳ người dùng nào đã đăng nhập vào cùng một hoạt động đăng nhập.
  2. đăng xuất khỏi hoạt động khác.

Dưới đây là những gì tôi đã thực hiện cho đến nay:

public class LoginActivity extends AppCompatActivity implements OnClickListener{ 

    private static final int RC_SIGN_IN = 9001; 
    private GoogleApiClient mGoogleApiClient; 
    private ConnectionResult mGoogleConnectionResult; 
    private Button login; 
    private ProgressDialog mProgressDialog; 
    private Context mContext; 
    private String mUri; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mContext= LoginActivity.this; 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     setContentView(R.layout.login_layout); 

     login= (Button) findViewById(R.id.lg_login_btn); 
     login.setOnClickListener(this); 
    } 

    @Override 
    public void onClick(View v) { 
     if(isOnline(mContext)){ 
      if(v.getId()== R.id.lg_login_btn) { 
       if(mGoogleApiClient!=null){ 
        mGoogleApiClient.disconnect(); 
       } 
      GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestScopes(new Scope(Scopes.PLUS_LOGIN)) 
      .requestEmail() 
      .build(); 

    mGoogleApiClient = new GoogleApiClient.Builder(mContext.getApplicationContext()) 
      .enableAutoManage(this , mGPlusConnectionFailedListener) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
      .addApi(Plus.API) 
      .build(); 

     signOutGPlus(); 
     Intent lSignInIntent= Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); 
     startActivityForResult(lSignInIntent, RC_SIGN_IN); 

      } 
     } else{ 
      showAlertDialog(mContext, "Error", "Please check internet connection"); 
     } 
    } 
    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     logD("&&onActivityResult", "requestCode: "+requestCode);  // first 

     if (requestCode == RC_SIGN_IN) { 
      if(resultCode == RESULT_OK){ 
       showProgressDialog(); 
       getGPlusUserInfo(data); 
      } else { 
       logD("&&onActivityResult", "requestCode: RESULT_ NOT Ok"+requestCode); 
      } 
     } 
    } 

    GoogleApiClient.OnConnectionFailedListener mGPlusConnectionFailedListener= new GoogleApiClient.OnConnectionFailedListener() { 
     @Override 
     public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
      logD("&&mGPlusConnectionFailedListener", "onConnectionFailed"); 
     } 
    }; 

    private void getGPlusUserInfo(Intent data){ 
     GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
     handleSignInResult(result); 
    } 

    private void handleSignInResult(GoogleSignInResult result) { 
     Log.d("&&handleSignInResult", "handleSignInResult:" + result.isSuccess()); 
     if (result.isSuccess()) { 
      // Signed in successfully, show authenticated UI. 
      String lDisplayName=""; 
      String lEmail=""; 
      String lFirstName=""; 
      String lLastName=""; 
      String lGender=""; 

      // G+ 
      if (mGoogleApiClient.hasConnectedApi(Plus.API)) { 
       logD("&&GPlusUserInfo", "&hasConnectedApi--------------------------------"); 
       // Deprecated 
       Person person = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); 
       if(null != person) { 
        logD("&&GPlusUserInfo", "&--------------------------------"); 
        logD("&&GPlusUserInfo", "&Display Name: " + person.getDisplayName()); 
       lDisplayName= person.getDisplayName(); 
        logD("&&GPlusUserInfo", "Gender: " + person.getGender()); 
        if(person.getGender()< MyHalConstants.GENDER.length){ 
         lGender= MyHalConstants.GENDER[person.getGender()]; 
        } else{ 
         lGender= "Other"; 
        } 
       } 
      } 
      GoogleSignInAccount acct = result.getSignInAccount(); 

      if(null != acct) { 
       if (null != acct.getDisplayName()) { 
        logD("&&GPlusUserInfo", "&Display Name: " + acct.getDisplayName()); 
       } 
       lFirstName= acct.getGivenName(); 
       lLastName= acct.getFamilyName(); 
       // Views inside NavigationView's header 
       Uri uri = acct.getPhotoUrl();     
      } 
     } else { 
      // Signed out, show unauthenticated UI. 
      signOutGPlus(); 
     } 
    } 


    // sign - out 
    private void signOutGPlus(){ 
     logD("&&signOutGPlus", "signOutGPlus"); 
     if(null != mGoogleApiClient){ 
      mGoogleApiClient.connect(); 
      mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { 

       @Override 
       public void onConnected(@Nullable Bundle bundle) { 
        if(mGoogleApiClient.isConnected()) { 
         logD("&&signOutGPlus", "inside"); 
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
          new ResultCallback<Status>() { 
            @Override 
            public void onResult(@NonNull Status status) { 
             logD("&&signOutGPlus", "onResult"); 
             if(mGoogleApiClient.isConnected()){ 
             mGoogleApiClient.clearDefaultAccountAndReconnect(); 
              mGoogleApiClient.disconnect(); 
            } 
            // Deprecated 
            /*Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); 
            //Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient); 
            //revokeAccess();*/ 
            } 
           } 
        ); 
        } 
       } 

       @Override 
       public void onConnectionSuspended(int i) { 

       } 
      }); 
     } 
    } 

// Not used 
    private void revokeAccess() { 
    logD("&&revokeAccess", "revokeAccess"); 
    Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
      new ResultCallback<Status>() { 
        @Override 
        public void onResult(Status status) { 
         // ... 
        } 
       }); 
    } 

    private void showProgressDialog() { 
     if (mProgressDialog == null) { 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage(getString(R.string.loading)); 
      mProgressDialog.setIndeterminate(true); 
     } 

     mProgressDialog.show(); 
    } 

    private void hideProgressDialog() { 
     if (mProgressDialog != null && mProgressDialog.isShowing()) { 
      mProgressDialog.hide(); 
     } 
    } 

    private void showAlertDialog(Context pContext, String pTitle, String pMessage){ 
     AlertDialog.Builder ldialogBuilder= new AlertDialog.Builder(pContext); 
     ldialogBuilder.setTitle(pTitle) 
      .setMessage(pMessage) 
     .setPositiveButton("Ok", null); 
     ldialogBuilder.show(); 
    } 

    private void dismissDialog(){ 
     if(null != mProgressDialog){ 
      mProgressDialog.dismiss(); 
      mProgressDialog= null; 
     } 
    } 
} 

Đối với dấu hiệu ra từ hoạt động khác nhau, không ai trong số các câu trả lời mà tôi đi qua xác định làm thế nào để initilaize mGoogleApiClient trong hoạt động mới .

Đối với dấu hiệu ra nếu tôi thực hiện vào mã bên dưới:

private GoogleApiClient mGoogleApiClient; 

// sign - out 
private void signOutGPlusFromDifferentActivity(){ 
    logD("&&signOutGPlus", "signOutGPlus"); 
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestScopes(new Scope(Scopes.PLUS_LOGIN)) 
      .requestEmail() 
      .build(); 

    mGoogleApiClient = new GoogleApiClient.Builder(mContext.getApplicationContext()) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
      .addApi(Plus.API) 
      .build(); 
    if(null != mGoogleApiClient){ 
     mGoogleApiClient.connect(); 
     mGoogleApiClient.registerConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { 
      @Override 
      public void onConnected(@Nullable Bundle bundle) { 
       if(mGoogleApiClient.isConnected()) { 
        logD("&&signOutGPlus", "inside"); 
        Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
          new ResultCallback<Status>() { 
           @Override 
           public void onResult(@NonNull Status status) { 
            logD("&&signOutGPlus", "onResult"); 
            if(mGoogleApiClient.isConnected()){ 
             mGoogleApiClient.clearDefaultAccountAndReconnect(); 
             mGoogleApiClient.disconnect(); 
            } 
           } 
          } 
        ); 
       } 
      } 
      @Override 
      public void onConnectionSuspended(int i) { 

      } 
     }); 
    } 
} 

Nó ném lỗi.

Bằng cách xóa phần đăng xuất khỏi hoạt động Đăng nhập, tôi có thể đăng nhập chính xác từ GPlus.

Gradle:

compile 'com.google.android.gms:play-services-auth:9.2.1' 
compile 'com.google.android.gms:play-services:9.2.1' 

LƯU Ý: từ hoạt động đăng nhập tôi có thể đăng nhập từ một trong hai google cộng hoặc mặt-book.

Hoạt động A (Đăng nhập từ g + hoặc fb).

Sau khi đăng nhập, người dùng được chuyển hướng đến Hoạt động B, từ người dùng Hoạt động B có thể đăng xuất khỏi cổng thích hợp (g + hoặc fb).

Phần Facebook được thực hiện. Chỉ còn lại là g +.

Vui lòng trợ giúp khi đăng xuất một cách chính xác trong cả hai trường hợp B BYNG CÁCH SỬ DỤNG API LOG LOG LOGOUT GOOGLE CẬP NHẬT.

+0

Bạn có thể sử dụng cho google + đăng nhập [https: // www .learn2crack.com/2013/12/android-google-plus-api-example.html]. Để đăng xuất, bạn có thể sử dụng mã này '@Override void công khai onClick (Chế độ xem) { nếu (xem.getId() == R.id.sign_out_button) { nếu (mGoogleApiClient.isConnected()) { Plus.AccountApi .clearDefaultAccount (mGoogleApiClient); mGoogleApiClient.disconnect(); mGoogleApiClient.connect(); } } } ' –

+0

@One Punch Man, tôi đã thêm giải pháp làm việc cho sự cố của bạn. Tôi gặp phải vấn đề tương tự cách đây vài ngày. Giải pháp này chắc chắn sẽ hoạt động. Hãy thử giải pháp và chấp nhận câu trả lời nếu nó giúp :) :) – oathkeeper

+0

Bạn có thể giải thích thêm chút ít vấn đề. –

Trả lời

2

Làm điều này trong hoạt động bạn thứ hai .Nếu bạn đang tiết kiệm bất kỳ sở thích về đăng nhập vào các hoạt động đầu tiên sau đó rõ ràng nó trên logout nhấp chuột

package com.ccc.bbbb; 

import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; 
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; 
import com.google.android.gms.common.api.ResultCallback; 
import com.google.android.gms.plus.People; 
import com.google.android.gms.plus.People.LoadPeopleResult; 
import com.google.android.gms.plus.Plus; 



//implement ConnectionCallbacks, OnConnectionFailedListener,ResultCallback<People.LoadPeopleResult> 

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

    public static boolean isLogout=false; 
    GoogleApiClient mGoogleApiClient; 


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

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

      //Logout button click 


        if(networkCheck.isNetworkAvailable(HomeActivity.this)) 
        { 
         Log.d(TAG, "logout if condition working...."); 


          isLogout=true; 

          if(mGoogleApiClient.isConnected()) 
          { 
           Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); 
           mGoogleApiClient.disconnect(); 
           mGoogleApiClient.connect(); 
          } 
          Toast.makeText(HomeActivity.this, "you are logged out", Toast.LENGTH_SHORT).show(); 

          Intent intent=new Intent(HomeActivity.this,MainActivity.class); 
          startActivity(intent); 
          finish(); 

         } 



//override below methods and copy those codes 

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

     } 


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

     } 


     @Override 
     public void onConnected(@Nullable 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(); 

     } 

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

     } 
     @Override 
     protected void onStop() 
     { 
      // TODO Auto-generated method stub 
      super.onStop(); 
      if (mGoogleApiClient.isConnected()) { 
       mGoogleApiClient.disconnect(); 
      } 
      if (mDialog.isShowing()) { 
       mDialog.dismiss(); 
      } 

     } 




} 
0

Khi Tôi đã đăng xuất, vào lần đăng nhập tiếp theo, tôi muốn người dùng chọn tài khoản google có sẵn để đăng nhập lại.

Bí quyết là để clearDefaultAccountAndReconnect các GoogleApiClient chỉ sau khi người dùng nhấp vào Google nút Đăng nhập để đăng nhập. Điều này đảm bảo rằng tất cả tài khoản Google có sẵn luôn được hiển thị bất cứ khi nào bạn nhấp vào Nút Đăng nhập.

Bước 1: Khởi tạo GoogleAPIClient và thiết lập OnClickListener để googleSignInButton trong Hoạt động onCreate()

private GoogleApiClient mApiClient; 

private void initializeGoogleSignIn() { 
    GoogleSignInOptions signInOptions = new GoogleSignInOptions 
      .Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestProfile() 
      .build(); 

    mApiClient = new GoogleApiClient.Builder(this) 
      .enableAutoManage(this, this) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions) 
      .build(); 

    SignInButton googleSignInButton = (SignInButton) findViewById(R.id.google_sign_in); 

    googleSignInButton.setOnClickListener(this); 
} 

Bước 2: Xử lý Google Đăng nhập qua onClick của bạn phương pháp()

@Override 
public void onClick(View v) { 

    switch (v.getId()) { 
     case R.id.google_sign_in: 

      if (mApiClient.isConnected()) { 
       mApiClient.clearDefaultAccountAndReconnect(); 
      } else { 
       mApiClient.connect(); 
      } 

      Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mApiClient); 
      startActivityForResult(signInIntent, RC_SIGN_IN); 

      break; 
    } 
} 

MISCALLANEOUS

// Make sure you connect and disconnect the GoogleApiClient in onStart and onStop lifecycle methods 
@Override 
protected void onStart() { 
    super.onStart(); 
    mApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    if (mApiClient.isConnected()) 
     mApiClient.disconnect(); 
} 



@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if (requestCode == RC_SIGN_IN) { 
      GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 

      if (result != null && result.isSuccess()) { 

       GoogleSignInAccount account = result.getSignInAccount(); 

       setAppPreferenceData(account.getId(), account.getEmail(), String.valueOf(account.getPhotoUrl()), account.getDisplayName()); 

       startActivity(new Intent(this, NavigationActivity.class)); 


       finish(); 
      } else { 
       mProgressLayout.setVisibility(View.GONE); 

       if (Utils.isNetworkAvailable(this)) 
        Toast.makeText(this, "Google Authentication Failed! Please try again", Toast.LENGTH_SHORT).show(); 
       else 
        Toast.makeText(this, "Network Error! Please connect to your wifi.", Toast.LENGTH_LONG).show(); 
      } 
     } 
    } 

Tại sao bạn cần nhiều phương thức gọi lại trong mã của bạn? Tôi cho rằng bạn phức tạp mã của bạn một chút. Bí quyết chính là ngắt kết nối và xóa tài khoản mặc định bất cứ khi nào người dùng cố gắng đăng nhập để đảm bảo rằng người đó luôn hiển thị danh sách tài khoản google hợp lệ. Tôi đã sử dụng cùng một quy trình, nó đã được thử, kiểm tra và làm việc.

Chỉ có một phương thức gọi lại cho trạng thái đăng nhập được sử dụng trong ứng dụng của tôi.

public class SignInActivity extends AppCompatActivity implements 
     GoogleApiClient.OnConnectionFailedListener { 
} 

@Override 
public void onConnectionFailed(ConnectionResult connectionResult) { 
    Toast.makeText(SignInActivity.this, "Google Play connection error", Toast.LENGTH_SHORT).show(); 
    mProgressLayout.setVisibility(View.GONE); 
} 
+0

Nó không bao giờ đi vào bên trong điều kiện kết nối. Điều gì về đăng nhập từ hoạt động khác nhau và làm thế nào để bạn xác định mApiClient trong hoạt động đăng xuất khác nhau. – OnePunchMan

+0

@OnePunchMan, Đăng xuất khỏi hoạt động khác khá khó khăn. Những gì bạn có thể thử là làm cho GoogleApiClient Singleton để nó có thể truy cập được trong suốt ứng dụng. Tuy nhiên, sau khi đối mặt với tình huống tương tự giống như bạn, ** Tôi thấy đó là cách tốt nhất để đăng xuất người dùng và xóa tài khoản của anh ta ngay trước khi anh ta chuẩn bị đăng nhập lại **. Tôi sẽ đăng thêm mã theo phần MISC trong câu trả lời của tôi. – oathkeeper

+1

Tôi đã thử trước đó mẫu mã mà bạn đã viết. Nó không bao giờ đi vào bên trong ** if (mApiClient.isConnected()) **. – OnePunchMan

0

Khi tôi đã đăng ký ra, lần sau tôi đăng nhập, tôi muốn người dùng chọn tài khoản google có sẵn để đăng nhập vào một lần nữa.

Đơn giản, đăng xuất người dùng và thu hồi quyền truy cập bất cứ khi nào người dùng nhấp vào nút đăng xuất. Lần tới, khi người dùng cố đăng nhập, họ sẽ được yêu cầu chọn tài khoản google ưa thích của họ.

Vì bạn đang đăng nhập và đăng xuất khỏi các hoạt động khác nhau, bạn sẽ kết thúc bằng mã trùng lặp. Thay vì sao chép mã, chỉ cần sử dụng lớp trợ giúp và khởi tạo Tùy chọn đăng nhập của Google và Ứng dụng khách Google API. Bây giờ, Bất cứ khi nào bạn muốn sử dụng Google API Client, bạn có thể khởi tạo lớp trợ giúp.

Trường hợp 1. Nếu bạn muốn đăng xuất trước khi đăng nhập, hãy sử dụng clearDefaultAccountAndReconnect.

Trường hợp 2. Để đăng xuất người dùng (Không quan trọng bất kỳ hoạt động nào), hãy sử dụng Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback.

Đây là github link cho dự án. Bạn có thể xem nếu bạn vẫn còn nghi ngờ.

1

Đối với Đăng-ra bạn có thể sử dụng phương pháp sau đây:

private void signOut() { 
    Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(
      new ResultCallback<Status>() { 
       @Override 
       public void onResult(Status status) { 
        Timber.d("Logged out"); 
       } 
      }); 
} 

Đối đăng nhập, bạn có thể làm theo các phương pháp:

public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { 
    this.activity = activity; 
    if (requestCode == RC_SIGN_IN) { 
     GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); 
     handleSignInResult(result); 
    } 

    /*For inintializing googleapiclient*/ 
    private void initGoogleClient() { 

    gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) 
      .requestEmail() 
      .build(); 

    googleApiClient = new GoogleApiClient.Builder(activity) 
      .enableAutoManage((FragmentActivity) activity /* FragmentActivity */, this /* OnConnectionFailedListener */) 
      .addApi(Auth.GOOGLE_SIGN_IN_API, gso) 
      .addOnConnectionFailedListener(this) 
      .addApi(Plus.API) 
      .addScope(new Scope(Scopes.PROFILE)) 
      .build(); 
} 

private void signIn() { 
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient); 
    activity.startActivityForResult(signInIntent, RC_SIGN_IN); 
} 
Các vấn đề liên quan