实现android的 google第三方登陆!

最近接到一个国外项目 要实现 Facebook twitter google+的第三方登陆  本来打算使用sharesdk的 但是这个第三方插件支持 facebook和twitter,但是在google上总是出现问题,无奈只能选择google的api实现。google的说明文档纯英文 你们都懂得 花费好久终于研究通了 不敢独享 就拿出来给大家分享下。

我这里使用的开发工具是IDEA 下面就是步骤了


上图是原理 下面就是干货 步骤

首先在google developer console创建一个专案



输入专案名 建议和你的项目名一致


之后要填写同意书


这一步比较关键  套件名称就是项目包名 SHA1密码 你可以自己生成,用keytool工具来生成 最后这个秘钥放在这个位置 同时你项目也要绑定秘钥。




最后千万别忘了开启google+服务的api接口 我之前就是忘了 总是获取不到登陆后的用户信息。



这里准备工作只进行了一部分 还有下载最新版本的 google服务包,通过android manager下载。然后导入google  play services lib文件 然后将它加到你的项目的dependency中

最后就是代码工作了

在androidmanifest中

1
2
<meta-data android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />
然后是main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent" android:layout_height="fill_parent">
    <com.google.android.gms.common.SignInButton
       android:id="@+id/sign_in_button"
       android:layout_centerInParent="true"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content" />
</RelativeLayout>

最后是activity

package com.example.TrueLife.view;


import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import com.example.TrueLife.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
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.common.api.Status;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;


import java.io.InputStream;


public class GoogleActivity extends Activity implements OnClickListener,
        ConnectionCallbacks, OnConnectionFailedListener {


    private static final int RC_SIGN_IN = 0;
    // Logcat tag
    private static final String TAG = "MainActivity";


    // Profile pic image size in pixels
    private static final int PROFILE_PIC_SIZE = 400;


    // Google client to interact with Google API
    private GoogleApiClient mGoogleApiClient;
    // private PlusClient mPlusClient;
    /**
     * A flag indicating that a PendingIntent is in progress and prevents us
     * from starting further intents.
     */
    private boolean mIntentInProgress;


    private boolean mSignInClicked;


    private ConnectionResult mConnectionResult;


    private SignInButton btnSignIn;
//    private Button btnSignOut, btnRevokeAccess;
//    private ImageView imgProfilePic;
//    private TextView txtName, txtEmail;
//    private LinearLayout llProfileLayout;
//    private WebView mWevView;
//
//    private int REQUEST_CODE = 10;
    public static final int RESULT_CODE =9;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
//        btnSignOut = (Button) findViewById(R.id.btn_sign_out);
//        btnRevokeAccess = (Button) findViewById(R.id.btn_revoke_access);
//        imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
//        txtName = (TextView) findViewById(R.id.txtName);
//        txtEmail = (TextView) findViewById(R.id.txtEmail);
//        llProfileLayout = (LinearLayout) findViewById(R.id.llProfile);
//        mWevView = (WebView)findViewById(R.id.google_webview);
       // initWebView();
        // Button click listeners
        btnSignIn.setOnClickListener(this);
//        btnSignOut.setOnClickListener(this);
//        btnRevokeAccess.setOnClickListener(this);


        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(Plus.API, Plus.PlusOptions.builder().build())
                .addScope(Plus.SCOPE_PLUS_PROFILE)
                .addScope(Plus.SCOPE_PLUS_LOGIN).build();
    }
//    public void initWebView(){
//        WebSettings webSettings = mWevView.getSettings();
//        webSettings.setJavaScriptEnabled(true);
//        mWevView.loadUrl("file:///android_asset/index.html");
//
//    }
    protected void onStart() {
        super.onStart();
        mGoogleApiClient.connect();
    }


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


    /**
     * Method to resolve any signin errors
     * */
    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }


    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
                    0).show();
            return;
        }


        if (!mIntentInProgress) {
            // Store the ConnectionResult for later usage
            mConnectionResult = result;


            if (mSignInClicked) {
                // The user has already clicked 'sign-in' so we attempt to
                // resolve all
                // errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int responseCode,
                                    Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }


            mIntentInProgress = false;


            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }


    @Override
    public void onConnected(Bundle arg0) {
        mSignInClicked = false;
        //Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
        /* This Line is the key */


        // Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(this);
        // Get user's information
        getProfileInformation();


        // Update the UI after signin
        updateUI(true);


    }


    /**
     * Updating the UI, showing/hiding buttons and profile layout
     * */
    private void updateUI(boolean isSignedIn) {
//        if (isSignedIn) {
//            btnSignIn.setVisibility(View.GONE);
//            btnSignOut.setVisibility(View.VISIBLE);
//            btnRevokeAccess.setVisibility(View.VISIBLE);
//            llProfileLayout.setVisibility(View.VISIBLE);
//          //  mWevView.setVisibility(View.VISIBLE);
//
//
//        } else {
//            btnSignIn.setVisibility(View.VISIBLE);
//            btnSignOut.setVisibility(View.GONE);
//            btnRevokeAccess.setVisibility(View.GONE);
//            llProfileLayout.setVisibility(View.GONE);
//        }
    }


    /**
     * Fetching user's information name, email, profile pic
     * */
    private void getProfileInformation() {
        try {
            //  Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback((ResultCallback<com.google.android.gms.plus.People.LoadPeopleResult>) this);


            if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
                Person currentPerson = Plus.PeopleApi
                        .getCurrentPerson(mGoogleApiClient);
                String personName = currentPerson.getDisplayName();
                String personPhotoUrl = currentPerson.getImage().getUrl();
                String personGooglePlusProfile = currentPerson.getUrl();
                String email = Plus.AccountApi.getAccountName(mGoogleApiClient);


                Log.e(TAG, "Name: " + personName + ", plusProfile: "
                        + personGooglePlusProfile + ", email: " + email
                        + ", Image: " + personPhotoUrl);


               // txtName.setText(personName);
               // txtEmail.setText(email);


                Intent intent=new Intent();
                intent.putExtra("personName", personName);
                intent.putExtra("Image",personPhotoUrl);
                setResult(RESULT_CODE, intent);
                this.finish();
//                mWevView.setVisibility(View.VISIBLE);
//                String call = "javascript:sumToJava('"+personName+"','"+email+"')";
//                mWevView.loadUrl(call);
                // by default the profile url gives 50x50 px image only
                // we can replace the value with whatever dimension we want by
                // replacing sz=X
                personPhotoUrl = personPhotoUrl.substring(0,
                        personPhotoUrl.length() - 2)
                        + PROFILE_PIC_SIZE;


             //   new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);


            } else {
                Toast.makeText(getApplicationContext(),
                        "Person information is null", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onConnectionSuspended(int arg0) {
        mGoogleApiClient.connect();
        updateUI(false);
    }


    // @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }


    /**
     * Button on click listener
     * */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sign_in:
                // Signin button clicked
                signInWithGplus();
                break;
//            case R.id.btn_sign_out:
//                // Signout button clicked
//                signOutFromGplus();
//                break;
//            case R.id.btn_revoke_access:
//                // Revoke access button clicked
//                revokeGplusAccess();
//                break;
        }
    }


    /**
     * Sign-in into google
     * */
    private void signInWithGplus() {
        if (!mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        }
    }


    /**
     * Sign-out from google
     * */
    private void signOutFromGplus() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            updateUI(false);
        }
    }


    /**
     * Revoking access from google
     * */
    private void revokeGplusAccess() {
        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
                    .setResultCallback(new ResultCallback<Status>() {
                        @Override
                        public void onResult(Status arg0) {
                            Log.e(TAG, "User access revoked!");
                            mGoogleApiClient.connect();
                            updateUI(false);
                        }


                    });
        }
    }


    /**
     * Background Async task to load user profile picture from url
     * */
    private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;


        public LoadProfileImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }


        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }


        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }


}

转载的话 请说明转载出处哈 

如果有问题建议研究下google的文档 或者在google搜索 相关的源码

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值