over 2 years ago

Google、Facebook的強大已經不在話下了,許多人開發App也都直接使用這兩種登入方法,
然而Google總是特別難以登入? 其實也就是步驟有點繁雜...
下面開始手把手的教學,不要跟我說學不會唷!(OS:愛的小手已準備)

Step 1. 建立keystore

1. 開啟CMD(系統管理員)並且進入C:\Program Files\Java\jer*\bin後,輸入下列

keytool -genkey -v -keystore my-release-key.keystore
-alias alias_name -keyalg RSA -keysize 2048 -validity 10000

開始建立keystore直至完成

2. 查詢keystore資料

keytool -list -v -keystore "你的keystore位置"

Step 2. 進入Google Developers Console並且建立專案


Step 3. 建立Oauth Client ID



Step 4. 開啟Google+ API

Code

Gradle

compile 'com.google.android.gms:play-services:7.3.0'

XML

Permissions

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />

Meta-data

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

Java

程式碼部分是參考(http://www.androidhive.info/2014/02/android-login-with-google-plus-account-1/)

package com.kuo.googlesignexample;

import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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.plus.Plus;
import com.google.android.gms.plus.model.people.Person;


public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    private static final int RC_SIGN_IN = 0;
    private static final int PROFILE_PIC_SIZE = 400;

    private boolean mIntentInProgress;
    private boolean mSignInClicked;

    private Toolbar toolbar;
    private SignInButton btnSignIn;
    private ImageView personPic;
    private TextView profile;
    private GoogleApiClient mGoogleApiClient;
    private ConnectionResult mConnectionResult;

    private String personName = "";
    private String personPhotoUrl  = "";
    private String personGooglePlusProfile  = "";
    private String email  = "";

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

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        btnSignIn = (SignInButton) findViewById(R.id.btn_sign_in);
        personPic = (ImageView) findViewById(R.id.personPic);
        profile = (TextView) findViewById(R.id.profile);

        toolbar.setTitle("Google Sign Example");
        setSupportActionBar(toolbar);

        btnSignIn.setOnClickListener(onClickListener);

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

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

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

    private void resolveSignInError() {
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (IntentSender.SendIntentException e) {
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {

        Log.d("result", result.toString());

        if (!result.hasResolution()) {
            GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
            return;
        }

        if (!mIntentInProgress) {
            mConnectionResult = result;
            if (mSignInClicked) {
                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) {

        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
        Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

        personName = currentPerson.getDisplayName();
        personPhotoUrl = currentPerson.getImage().getUrl();
        personGooglePlusProfile = currentPerson.getUrl();
        email = Plus.AccountApi.getAccountName(mGoogleApiClient);

        personPhotoUrl = personPhotoUrl.substring(0, personPhotoUrl.length() - 2) + PROFILE_PIC_SIZE;

        new DownloadImageTask((ImageView) findViewById(R.id.personPic)).execute(personPhotoUrl);

        profile.setText("personName : " + personName + "\n" + "personGooglePlusProfile : " + personGooglePlusProfile + "\n" + "email : " + email);

    }

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

    private SignInButton.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mGoogleApiClient.isConnecting()) {
                mSignInClicked = true;
                resolveSignInError();
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
}

江將~

程式碼這部分其實很簡單,只要上述設定都有成功,自然而然可以取得登入與訊息,
有些人會有疑問,為什麼可以登入卻沒辦法取得登入者訊息,主要原因在於沒有開啟GooglePlus Api,
開啟後也不要急,需要點時間就可以成功了。

GitHub. 完整的專案

← [Android] 自製控件 CoolDatePicker 日期選擇器 [Android] SampleCalculator 簡單計算機 →
 
comments powered by Disqus