Full Source Code Download Here:
https://github.com/sanjaymangaroliya/LoginWithGooglePlus
MainActivity.java
package com.sanjay.loginwithgoogleplus;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.OptionalPendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener {
private Button btn_sign_in, btn_logout;
private ImageView img_profile;
private TextView tv_info;
//private SignInButton btn_sign_in_default;
private static final int RC_SIGN_IN = 100;
private GoogleApiClient mGoogleApiClient;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
GoogleSignInOptions 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();
// Customizing G+ button
//btn_sign_in_default.setSize(SignInButton.SIZE_STANDARD);
//btn_sign_in_default.setScopes(gso.getScopeArray());
initUI();
}
private void initUI() {
TextView tvTitle = findViewById(R.id.tv_title);
tvTitle.setText(getResources().getString(R.string.app_name));
//btn_sign_in_default = findViewById(R.id.btn_sign_in_default);
btn_sign_in = findViewById(R.id.btn_sign_in);
btn_logout = findViewById(R.id.btn_logout);
img_profile = findViewById(R.id.img_profile);
tv_info = findViewById(R.id.tv_info);
}
public void onClickSignIn(View view) {
if (Utils.isNetworkAvailable(this)) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
} else {
Utils.showAlertDialog(this, getResources().getString(R.string.alert)
, getResources().getString(R.string.internet_error));
}
}
private void handleSignInResult(GoogleSignInResult result) {
if (result.isSuccess()) {
updateUI(true);
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
Uri personPhotoUrl = acct.getPhotoUrl();
StringBuilder stringBuilder = new StringBuilder();
if (Utils.isNotEmptyString(personName)) {
stringBuilder.append("Name: " + personName);
}
if (Utils.isNotEmptyString(personEmail)) {
stringBuilder.append("\nEmail: " + personEmail);
}
tv_info.setText(stringBuilder.toString());
//Profile Picture
if (personPhotoUrl != null) {
Glide.with(getApplicationContext()).load(personPhotoUrl)
.thumbnail(0.5f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(img_profile);
}
} else {
updateUI(false);
}
}
@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);
}
}
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(true);
}
progressDialog.show();
}
private void hideProgressDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.hide();
}
}
private void updateUI(boolean isSignedIn) {
if (isSignedIn) {
btn_sign_in.setVisibility(View.GONE);
btn_logout.setVisibility(View.VISIBLE);
img_profile.setVisibility(View.VISIBLE);
tv_info.setVisibility(View.VISIBLE);
} else {
btn_sign_in.setVisibility(View.VISIBLE);
btn_logout.setVisibility(View.GONE);
img_profile.setVisibility(View.GONE);
tv_info.setVisibility(View.GONE);
}
}
public void onClickLogout(View view) {
if (mGoogleApiClient.isConnected()) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
updateUI(false);
}
});
}
}
}
Utils.java
package com.sanjay.loginwithgoogleplus;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.widget.Toast;
public class Utils {
public static boolean isNetworkAvailable(Context context) {
if (context == null) {
return false;
}
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
public static void showToast(Context activity, String strMsg) {
Toast toast = Toast.makeText(activity, strMsg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
public static void showAlertDialog(Context context, String title, String msg) {
AlertDialog.Builder adb = new AlertDialog.Builder(context);
adb.setTitle(title);
adb.setMessage(msg);
adb.setCancelable(false);
adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
adb.create().show();
}
public static boolean isNotEmptyString(String str) {
if (str != "" && str != null && str.trim().length() > 0
&& !str.equalsIgnoreCase("null")) {
return true;
}
return false;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:fitsSystemWindows="true">
<include layout="@layout/toolbar" />
<android.support.v4.widget.NestedScrollView
android:id="@+id/nested_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<RelativeLayout
android:id="@+id/rl_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<!-- <com.google.android.gms.common.SignInButton
android:id="@+id/btn_sign_in_default"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:onClick="onClickSignIn"
android:visibility="gone" />-->
<Button
android:id="@+id/btn_sign_in"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:onClick="onClickSignIn"
android:text="@string/sign_in"
android:textColor="@color/white"
android:visibility="visible" />
<Button
android:id="@+id/btn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_sign_in"
android:layout_marginTop="20dp"
android:background="@color/colorPrimary"
android:gravity="center"
android:onClick="onClickLogout"
android:text="@string/logout"
android:textColor="@color/white"
android:visibility="gone" />
<ImageView
android:id="@+id/img_profile"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/btn_logout"
android:layout_marginTop="20dp"
android:src="@mipmap/ic_launcher"
android:visibility="gone" />
<TextView
android:id="@+id/tv_info"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_logout"
android:layout_marginLeft="10dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="@+id/img_profile"
android:text="@string/name"
android:textColor="@color/colorPrimary"
android:textSize="16dp"
android:visibility="gone" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
toolbar.xml
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay">
<TextView
android:id="@+id/tv_title"
style="@style/tv_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sanjay.loginwithgoogleplus">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimary</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="windowActionBar">true</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<style name="tv_title">
<item name="android:layout_gravity">center</item>
<item name="android:textColor">@color/white</item>
<item name="android:textSize">20sp</item>
<item name="android:textAllCaps">false</item>
<item name="android:textStyle">normal</item>
</style>
<style name="textView">
<item name="android:singleLine">true</item>
<item name="android:textAllCaps">false</item>
</style>
</resources>
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.sanjay.loginwithgoogleplus"
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
//Support Design
compile 'com.android.support:design:26+'
//Google Auth
compile 'com.google.android.gms:play-services-auth:11.8.0'
//Glide Image
compile 'com.github.bumptech.glide:glide:3.7.0'
}
apply plugin: 'com.google.gms.google-services'
No comments:
Post a Comment