阅读背景:

Android:Google在没有Cloud Code的情况下登录与Sashido(Parse.com SDK)的集成

来源:互联网 

I'm writing this question and answer because I haven't seen a full solution to the integration of Google sign in on Android using Facebook's Parse SDK (or Sashido in my case) as a back-end without cloud code.

我正在写这个问题和答案,因为我还没有看到使用Facebook的Parse SDK(或者我的Sashido)作为没有云代码的后端在Android上集成Google登录的完整解决方案。

Related Questions:


How would one go about integrating Google Sign in with Parse back-end without Cloud Code?

如何在没有Cloud Code的情况下将Google登录与Parse后端集成?

1 个解决方案

#1


1  

First of all, follow the steps provided by Android Developers on starting and implementing the integration.

首先,按照Android开发人员提供的步骤开始和实现集成。

  1. Start Integrating Google Sign-In into Your Android App
  2. 开始将Google登录集成到您的Android应用中

  3. Integrating Google Sign-In into Your Android App
  4. 将Google登录集成到您的Android应用中

  5. In the onCreate your activity you need to build the GoogleSignInOptions

    在onCreate您的活动中,您需要构建GoogleSignInOptions

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

You can get your web_client_id when you add Google Services to your project to your Google Developers account. Find out more at: Creating a Google API Console project and client ID

将Google服务添加到Google Developers帐户的项目时,您可以获取web_client_id。有关详细信息,请参阅:创建Google API控制台项目和客户端ID

  1. Build your GoogleApiClient (make it a global instance private GoogleApiClient mGoogleApiClient;)

    构建您的GoogleApiClient(将其设为全局实例私有GoogleApiClient mGoogleApiClient;)

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                    Log.e("Failed", "failed" + connectionResult.getErrorMessage());
                }
            })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
    
  2. Listen out for the click on the dedicated button for your Google sign in and then start a Auth.GoogleSignInApi.getSignIntent(mGoogleApiClient);

    聆听点击Google登录的专用按钮,然后启动Auth.GoogleSignInApi.getSignIntent(mGoogleApiClient);

    case R.id.btn_google: Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent, RC_SIGN_IN); break;

    case R.id.btn_google:Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); startActivityForResult(signInIntent,RC_SIGN_IN);打破;

Make sure you've assigned a value to RC_SIGN_IN (I've done 1000)

确保你已经为RC_SIGN_IN分配了一个值(我已经完成了1000)

  1. Now start adding implementation to your onActivityResult method

    现在开始向onActivityResult方法添加实现

    // Result returned from launching the Intent from
    //   GoogleSignInApi.getSignInIntent(...);
    if (requestCode == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    } else {
        ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
    }
    

Now to handle the sign in request:

现在处理登录请求:

`private void handleSignInResult(GoogleSignInResult result) {
        Log.e("handleSignIn", "handleSignInResult:" + result.isSuccess());
        if (result.isSuccess()) {
            // Signed in successfully, show authenticated UI.
            final GoogleSignInAccount acct = result.getSignInAccount();
            if (acct != null) {
                ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
                query.setLimit(10000);
                query.whereEqualTo("email", acct.getEmail());
                query.findInBackground(new FindCallback<ParseObject>() {
                    @Override
                    public void done(List<ParseObject> objects, ParseException e) {
                        if (e == null) {
                            if (objects.size() == 0) {
                                saveNewUserGoogle(acct);
                            } else {
                                loginGoogleUser(objects.get(0), acct);
                            }
                        } else {
                            saveNewUserGoogle(acct);
                        }
                    }
                });
            }
        } else {
            Log.e("failed", "failed to sign in");
            // Signed out, show unauthenticated UI.
        }
    }`

So what this method does is if the request to the GoogleSignIn Request is successful, get the account details, query the _User table in your database and to see if the email with the account matches. If it does, Log the user in.

因此,此方法的作用是,如果对GoogleSignIn请求的请求成功,请获取帐户详细信息,查询数据库中的_User表以及查看具有该帐户的电子邮件是否匹配。如果是,请将用户登录。

private void loginGoogleUser(ParseObject j, GoogleSignInAccount acct) { ParseUser.logInInBackground(j.getString("username"), String.valueOf(acct.getId()), new LogInCallback() { public void done(ParseUser user, ParseException e) { if (user != null) { Intent i = new Intent(AllLoginActivity.this, MainActivity.class); startActivity(i); finish(); } else { Log.e("failed", "could not be validated"); } } }); }

private void loginGoogleUser(ParseObject j,GoogleSignInAccount acct){ParseUser.logInInBackground(j.getString(“username”),String.valueOf(acct.getId()),new LogInCallback(){public void done(ParseUser user,ParseException e) {if(user!= null){Intent i = new Intent(AllLoginActivity.this,MainActivity.class); startActivity(i); finish();} else {Log.e(“failed”,“无法验证”) );}}}); }

else sign the user up:

否则签署用户:

private void saveNewUserGoogle(GoogleSignInAccount acct) {
        google = true;
        final ParseUser user = new ParseUser();
        String mFullName = acct.getDisplayName();
        String mEmail = acct.getEmail();
        String mProfilePic = String.valueOf(acct.getPhotoUrl());
        String mUsername = acct.getId();
        String password = acct.getId();
        user.setUsername(mUsername);
        user.setEmail(mEmail);
        user.setPassword(password);
        user.put("userEmail", mEmail);
        user.put("uniqueID", mUsername);
        user.put("name", mFullName);
        user.put("loginMethod", "Google");
        user.put("profilePicture", mProfilePic);
        user.signUpInBackground(new SignUpCallback() {
                public void done(ParseException e) {
                    if (e == null) {
                        Log.e("SaveTest", "Successful");
                        //sign user up
                    } else {
                        switch (e.getCode()) {
                            case ParseException.USERNAME_TAKEN:
                                Toast.makeText(context, "Sorry, this username has already been taken.", Toast.LENGTH_SHORT).show();
                                break;
                            case ParseException.USERNAME_MISSING:
                                Toast.makeText(context, "Sorry, a username is needed", Toast.LENGTH_SHORT).show();
                                break;
                            case ParseException.PASSWORD_MISSING:
                                Toast.makeText(context, "Sorry, a password is needed.", Toast.LENGTH_SHORT).show();
                                break;
                            case ParseException.OBJECT_NOT_FOUND:
                                Toast.makeText(context, "invalid credentials", Toast.LENGTH_SHORT).show();
                                break;
                            case ParseException.CONNECTION_FAILED:
                                Toast.makeText(context, "Sorry, internet is needed.", Toast.LENGTH_SHORT).show();
                                break;
                            default:
                                Log.d("Testing", e.getLocalizedMessage());
                                break;
                        }
                    }
                }
            });

    }

So for this if you set the password on Parse as the clientID it'll be unique to that user and can be read by Parse and given by Google.

因此,如果您将Parse上的密码设置为clientID,则该密码对该用户是唯一的,并且可以由Parse读取并由Google提供。

Note: I'm setting the username as the Google Identifier and then when they have successfully connected and signed up I display a username dialog box where they enter a username, so it can be displayed as something in plain text rather than numerics.

注意:我将用户名设置为Google标识符,然后当他们成功连接并注册后,我会显示一个用户名对话框,在其中输入用户名,因此它可以显示为纯文本而非数字。


分享到: