在Android应用中集成Google登录按钮

时间:2016-11-06 10:01:05

标签: android android-activity google-signin

好的,我正在尝试使用Google https://developers.google.com/identity/sign-in/android/sign-in?configured=true

中的代码

LoginActivity

CREATE TABLE [user]
(
ID INT PRIMARY KEY
LastLogin Time,
Admin BIT, 
Email VARCHAR(50) NOT NULL UNIQUE,

-- "auth" for "authentification" 
auth algo CHECK(algo='sha1' OR algo='sha256'),
auth stretch INT,
auth salt VARCHAR(32),
auth hash VARCHAR(24)
)

的Manifest.xml

GoogleApiClient mGoogleApiClient;
GoogleSignInOptions gso;
SignInButton signIn_btn;
private static final int RC_SIGN_IN = 0;
ProgressDialog progress_dialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    buidNewGoogleApiClient();
    setContentView(R.layout.activity_login);
    customizeSignBtn();
    setBtnClickListeners();


    mNotificationManager = (NotificationManager) this.getApplicationContext().getSystemService(this.NOTIFICATION_SERVICE);

    Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Big Daddy St.ttf");
    Typeface myTypeFaceFacebook = Typeface.createFromAsset(getAssets(), "Big Daddy St.ttf");


    mainImage = (ImageView) findViewById(R.id.imageView1);

    TextView textView1 = (TextView) findViewById(R.id.textView1);
    textView1.setOnClickListener(this);
    textView1.setTypeface(myTypeFace);

    Button button = (Button) findViewById(R.id.btn_login_facebook);
    button.setOnClickListener(this);
    button.setTypeface(myTypeFaceFacebook);



}

private void buidNewGoogleApiClient() {

    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();
}

private void customizeSignBtn() {

    signIn_btn = (SignInButton) findViewById(R.id.sign_in_button);
    signIn_btn.setSize(SignInButton.SIZE_STANDARD);
    signIn_btn.setScopes(gso.getScopeArray());

}

private void setBtnClickListeners() {
    // Button listeners
    signIn_btn.setOnClickListener(this);


}

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

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

@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 == RC_SIGN_IN) {
        if (resultCode != RESULT_OK) {



        }
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        getSignInResult(result);
    }
}

private void getSignInResult(GoogleSignInResult result) {
GoogleSignInStatusCodes.getStatusCodeString(result.getStatus().getStatusCode());


    if (result.isSuccess()) {

        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();
        Toast.makeText(this, "email: " + acct.getEmail(), Toast.LENGTH_SHORT).show();

        //TextView user_name= (TextView)findViewById(R.id.userName);
        // TextView email_id= (TextView)findViewById(R.id.emailId);
        // user_name.setText("UserName: "+ acct.getDisplayName());
        // email_id.setText("Email Id: " + acct.getEmail());

        progress_dialog.dismiss();
    } else {
        // Signed out, show unauthenticated UI.
        try {


        } catch (Exception e) {
            Toast.makeText(this, "Exception: " +e.getMessage(), Toast.LENGTH_LONG).show();
        }

        //updateUI(false);
    }
}






@Override
public void onClick(View view) {




    if(view.getId() == R.id.textView1){
        Intent signupIntent = new Intent(this, SignUpScreen.class);
        startActivity(signupIntent);

    }

    if(view.getId() == R.id.btn_login_facebook){
        Intent intent = new Intent(this, todelete.class);

        //Notification
        // notificationWithButton();
        startActivity(intent);
    }
    if(view.getId()==R.id.sign_in_button){
        Toast.makeText(this, "start sign process", Toast.LENGTH_SHORT).show();
        gSignIn();


    }

}
private void gSignIn() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    startActivityForResult(signInIntent, RC_SIGN_IN);
  //  progress_dialog.show();
}


void notificationWithButton(){
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        // Prepare intent which is triggered if the  notification button is pressed
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Building the notifcation
        NotificationCompat.Builder nBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher) // notification icon
                .setContentTitle("Button notification") // notification title
                .setContentText("Expand to show the buttons...") // content text
                .setTicker("Showing button notification") // status bar message
                .addAction(R.drawable.common_google_signin_btn_icon_dark, "Accept", pIntent) // accept notification button
                .addAction(R.drawable.common_google_signin_btn_icon_dark_normal, "Cancel", pIntent); // cancel notification button

        mNotificationManager.notify(1001, nBuilder.build());

    } else {
        Toast.makeText(this, "You need a higher version", Toast.LENGTH_LONG).show();
    }
}


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

}

}

/>

build.gradle(Project)

 <uses-permission android:name="android.permission.INTERNET" />
    <!-- To access accounts configured on device -->
    <uses-permission android:name="android.permission.GET_ACCOUNTS" />
    <!-- To use account credentials -->
    <uses-permission android:name="android.permission.USE_CREDENTIALS" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WIFI" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version"

build.gradle(App)

  dependencies {
    classpath 'com.android.tools.build:gradle:2.1.3'
    classpath 'com.google.gms:google-services:3.0.0'

非常感谢您的帮助。

编辑:添加了GoogleSignInStatusCodes.getStatusCodeString(result.getStatus()。getStatusCode());  返回10,对应于DEVELOPER_ERROR。

我之前为Google地图创建了一个密钥,它包含在我的项目中(在清单文件中,元标记),现在我是否必须创建另一个密钥?如果是,我该如何包含它?

3 个答案:

答案 0 :(得分:0)

要调试这个,我会这样做:breakpoint / print来记录你成功登录后从谷歌回来的东西。这将告诉您数据的位置。

下一个活动是什么?看起来你是从谷歌开始做的事情,但开始你自己制作的东西会更有意义。

编辑过去了。一些想法:

googleSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
findViewById(R.id.sign_in_button).setOnClickListener(this);

// Can be done this way:
googleSignInButton = (SignInButton) findViewById(R.id.sign_in_button);
googleSignInButton.setOnClickListener(this);

这就是我做这样的事情:

SignInButton buttonGoogle = (SignInButton) findViewById(R.id.button_google);
assert buttonGoogle != null;
buttonGoogle.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
});

要成功登录Google,您需要以下内容: getResources()。getString(R.string.google)=&gt;从strings.xml中获取字符串

/**
 * Handling the result from Google.
 * @param result                    You know, tha package.
 */
private void handleSignInResult(GoogleSignInResult result) {
    Log.d("handleSignInResult:", "" + result.isSuccess());
    if (result.isSuccess()) {
        // Signed in successfully, show authenticated UI.
        GoogleSignInAccount acct = result.getSignInAccount();
        successfulLogin(getResources().getString(R.string.google),
                acct.getDisplayName(),
                acct.getId(),
                acct.getEmail());
    } else { // but is never used atm.
        String message = String.format(getResources().getString(R.string.communication_signed_out), getResources().getString(R.string.google));
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

答案 1 :(得分:0)

尝试以下代码

           private void handleSignInResult(GoogleSignInResult result) {
                Log.d(String.valueOf(LoginActivity.this), "handleSignInResult:" + result.isSuccess());
                if (result.isSuccess()) {
                    // Signed in successfully, show authenticated UI.
                    GoogleSignInAccount acct = result.getSignInAccount();
              if (acct != null) {

                        Intent iWelcomeActivity = new Intent(MainActivity.this, WelcomeActivity.class);
                        iWelcomeActivity.putExtra("USERNAME", acct.getDisplayName());
                        iWelcomeActivity.putExtra("EMAIL", acct.getEmail();
);
                        startActivity(iWelcomeActivity);
                    }
                } else {
                    // Signed out, show unauthenticated UI.
                    //updateUI(false);
                }
            }

当用户点击sigin按钮时,意图会提示用户选择要登录的Google帐户。   onActivityResult 方法,检索登录结果并调用handleSignInResult(GoogleSignInResult result)

如果登录成功,您可以致电getSignInAccount method以获取 GoogleSignInAccount对象,其中包含有关已登录用户的信息。 使用 GoogleSignInAccount对象acct.getDisplayName(),acct.getEmail()的形式检索信息,并将其传递给下一个活动,如上面的代码所示。

希望它会有所帮助

答案 2 :(得分:0)

我遇到同样的错误,直到找到this SO question。问题是如果您没有配置调试版本来使用发布签名密钥,它将使用默认的debugkeystore。如果您已正确设置API密钥,则无法匹配。显然,如果您使用发布签名密钥构建版本.apk,它会起作用,但如果您正在调试(在开发中),您可能忽略了这个过程。

解决方案

  1. 转到 构建&gt; 编辑构建类型...

  2. 签名选项卡上,创建您的发布签名密钥别名和密钥库的新条目。您可以随意命名,我使用&#39; 发布&#39;。

  3. 现在,在构建类型选项卡上,对于&#39; debug&#39;构建类型,签名配置设置为在步骤2中创建的任何内容。

  4. 点击 确定,再次再次运行

  5. 鲍勃是你的阿姨