Google 使用 android Studio 登录

Google Sign in with android Studio

我正在使用我为创建 JSON 文件而关注的 Google 帐户登录。我还集成了 JSON 文件和我的 project.But 我得到异常 account.getDisplayName throws nullPointException.

Google 登录码:

public class MainActivity extends AppCompatActivity implements 
View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
private SignInButton signInButton;
private GoogleApiClient client;
private static final int REQ_CODE = 9001;

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

    signInButton = (SignInButton)findViewById(R.id.btn_signin);

    GoogleSignInOptions options = new 
 GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN)
            .requestProfile()
            .requestEmail()
            .build();
    client = new GoogleApiClient.Builder(this).
            enableAutoManage(this,this).
            addApi(Auth.GOOGLE_SIGN_IN_API,options).build();

    signInButton.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.btn_signin:
            signIn();
            break;
    }
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}
    public void signIn(){
    Intent intent = Auth.GoogleSignInApi.getSignInIntent(client);
    startActivityForResult(intent,REQ_CODE);
}

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

 private void handleResult(GoogleSignInResult result) {
    if (result.isSuccess()){
        GoogleSignInAccount account = result.getSignInAccount();
        String name = account.getDisplayName();
            String email = account.getEmail();
            String image = account.getPhotoUrl().toString();
    }
}
}

这是我编译的库:

implementation 'com.google.android.gms:play-services-auth:16.0.1'

请指导我哪里做错了

试试这个:

    @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 == REQ_CODE) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);

            // G+
            Person person  = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
            System.out.println("Display Name: " + person.getDisplayName());
            System.out.println("Gender: " + person.getGender());
            System.out.println("AboutMe: " + person.getAboutMe());
            System.out.println("Birthday: " + person.getBirthday());
            System.out.println("Current Location: " + person.getCurrentLocation());
            System.out.println("Language: " + person.getLanguage());

        }
    }

如果您想要 google 的“用户名、电子邮件 ID、配置文件 URL、Google Id”。

您 "GoogleSignInOptions" 做错了。请将我的 GoogleSignInOptions 替换为您的 GoogleSignInOptions 代码以解决您的问题。

然后,你的解决方案在这里 -> 你应该按照下面的代码。

    private GoogleApiClient mGoogleApiClient;
    private static final int RC_SIGN_IN = 9001;
    private LinearLayout googleBtn;

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View view = inflater.inflate(R.layout.fragment_login, container, false);
           googleBtn = view.findViewById(R.id.googleBtn);


           GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken(getString(R.string.default_web_client_id))
                    .build();

           mGoogleApiClient = new GoogleApiClient.Builder(Objects.requireNonNull(getActivity()))
                .enableAutoManage(getActivity(), 0, connectionResult -> {
                    Snackbar.make(googleBtn, "Connection failed..", Snackbar.LENGTH_SHORT).show();
                    Log.e(TAG, "Google connection Error: " + connectionResult.getErrorMessage());
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                    @Override
                    public void onConnected(@Nullable Bundle bundle) {
                        //Log.e(TAG,"mGoogleApiClient is connected");
                        mGoogleApiClient.clearDefaultAccountAndReconnect();
                    }

                    @Override
                    public void onConnectionSuspended(int i) {

                    }
                })
                .build();
            }

        public void onClick(View v) {
        switch (v.getId()) {
               case R.id.googleBtn:
                       //stopAutoManage first otherwise throws exception Already managing a GoogleApiClient with id 0
                         if (mGoogleApiClient != null) {
        mGoogleApiClient.stopAutoManage(Objects.requireNonNull(getActivity()));
                         }
                loginWithGoogle();
                break;
         }

    public void loginWithGoogle() {
        Log.e(TAG, "is connected? " + mGoogleApiClient.isConnected());

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        Objects.requireNonNull(getActivity()).startActivityForResult(signInIntent, RC_SIGN_IN);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            handleSignInResult(result);
        }
    }


public void handleSignInResult(GoogleSignInResult result) {

        if (result.isSuccess()) {
            GoogleSignInAccount acct = result.getSignInAccount();
            // Get account information

            if (acct != null) {
                Name = acct.getDisplayName();
                if (acct.getEmail() != null) {
                    Email = acct.getEmail();
                } else {
                    Email = "";
                }

                SocialUserId = acct.getId();
                Gender = "";

                String idToken = acct.getIdToken();
                String profileURL = Objects.requireNonNull(acct.getPhotoUrl()).toString();

                String status = "Status: \nFullname: " + Name + "\n Email: " + Email + "\nProfile URI: " + profileURL;
                Log.i(TAG, "Google signin " + status);
                Log.i(TAG, "ID Token: " + idToken);
                Log.i(TAG, "ID: " + acct.getId());

                //TODO Temporary "acct.getCompId()" pass "idToken"

                checkIsUserExists();
            }

        } else {
            hideProgressBar();
            Log.e(TAG, "Failed!! Google Result " + result.getStatus());

            int status_code = result.getStatus().getStatusCode();
            switch (status_code) {
                case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
                    Snackbar.make(googleBtn, "Google sign in has been cancelled.", Snackbar.LENGTH_SHORT).show();
                    break;
                case GoogleSignInStatusCodes.NETWORK_ERROR:
                    Snackbar.make(googleBtn, "Application is unable to connect with internet", Snackbar.LENGTH_SHORT).show();
                default:
                    //AppUtils.showSnackBar(LandingActivity.this, btnLogin, GoogleSignInStatusCodes.getStatusCodeString(result.getStatus().getStatusCode()), R.integer.snackbar_duration_3sec);
                    break;
            }
        }
    }

您可以按照以下步骤在您的 Android 应用程序中集成 Google 登录

步骤 1. 实现库

 implementation 'com.google.android.gms:play-services-auth:17.0.0'

第 2 步。添加 google 登录按钮

<com.google.android.gms.common.SignInButton
    android:id="@+id/sign_in_button"
    android:layout_width="wrap_content"
    android:layout_gravity="center|center_vertical"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    />

第 3 步。在 activity.

中添加以下代码
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    signup = (SignInButton)findViewById(R.id.signup);
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();
    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent signInIntent = mGoogleSignInClient.getSignInIntent();
            startActivityForResult(signInIntent, google_login);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    Log.e("called", "called");
    if (requestCode == google_login) {
        Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
        handleSignInResult(task);
    }
}

private void handleSignInResult(Task completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);
        // Disaplay data on your screen
        Log.e("email", account.getEmail());
        Log.e("name", account.getDisplayName());
        Log.e("id", account.getId());

    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.e("signInResult", ":failed code=" + e.getStatusCode());
    }
}

您可以按照本教程完成实施:- Sign In with Google in your Android Application