Je développe une application sur Android et je veux permettre aux utilisateurs de se connecter avec leur compte Google. Comment puis-je atteindre cet objectif?
Vous voudrez peut-être authentifier l'utilisateur à l'aide de l'un des comptes Google déjà configurés sur votre appareil, à l'instar de certaines applications, suivez le lien ci-dessous -
"Authentification auprès des services OAuth2" - http://developer.Android.com/training/id-auth/authenticate.html
Télécharger un échantillon depuis Google - Gestionnaire de SDK Android/Extras/Services Google Play
En quelques étapes simples
C’est un autre lien qui explique bien le processus - http://Android-developers.blogspot.in/2013/01/verifying-back-end-calls-from-Android.html
vous pouvez suivre les étapes ci-dessous pour vous connecter à votre application
Ci-dessous le format de réponse de l'appel ci-dessus "userinfo"
{
"id": "ID",
"name": "NAME",
"given_name": "GiVEN NAME",
"family_name": "FAMILY_NAME",
"link": "https://plus.google.com/ID",
"picture": "https://PHOTO.jpg",
"gender": "GENDER",
"locale": "LOCALE"
}
Si vous voulez Email id avec cette réponse, vous devez modifier
SCOPE = "oauth2: https://www.googleapis.com/auth/userinfo.profile ";
à
SCOPE = "oauth2: https://www.googleapis.com/auth/userinfo.profilehttps://www.googleapis.com/auth/userinfo.email ";
dans cet échantillon
Jetez un coup d'œil à http://developer.Android.com/training/id-auth/index.html Vous y trouverez un tutoriel sur l'utilisation du gestionnaire de compte. (Plus spécifiquement http://developer.Android.com/reference/Android/accounts/AccountManager.html )
Commencez par insérer la ligne ci-dessous dans vos dépendances build.gradle
compile 'com.google.Android.gms:play-services:7.5.0'
Nous avons maintenant besoin des empreintes digitales SHA-1 que nous devons donner dans la console des développeurs Google.
L'outil de clé Java est utilisé pour générer l'empreinte SHA-1. Ouvrez votre invite de commande [Ouvrez C:\Program Files\Java\jdk\bin, puis appuyez sur les touches Maj + clic droit] et exécutez la commande suivante pour générer une empreinte SHA-1 et saisissez le mot de passe Android sous Android.
keytool -list -v -keystore "%USERPROFILE%\.Android\debug.keystore" -alias androiddebugkey -storepass Android -keypass Android
Pour vous authentifier et communiquer avec les API Google+, vous devez créer un projet Google Developers Console dans lequel vous devez activer l'API Google+ et créer un ID client OAuth 2.0.
Il est maintenant temps de déclarer les autorisations sur votre fichier mainfest . Voici à quoi ressemblera votre fichier manifeste après l’ajout des métadonnées et de toutes les autorisations.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:Android="http://schemas.Android.com/apk/res/Android"
package="com.androstock.loginwithgoogle" >
<uses-permission Android:name="Android.permission.INTERNET" />
<uses-permission Android:name="Android.permission.GET_ACCOUNTS" />
<uses-permission Android:name="Android.permission.USE_CREDENTIALS" />
<application
Android:allowBackup="true"
Android:icon="@mipmap/ic_launcher"
Android:label="@string/app_name"
Android:theme="@style/AppTheme" >
<activity
Android:name=".MainActivity"
Android:label="@string/app_name" >
<intent-filter>
<action Android:name="Android.intent.action.MAIN" />
<category Android:name="Android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Nous nous dirigeons maintenant vers notre classe MainActivity.Java où nous allons faire tout notre travail pour Google+ Login.
package com.androstock.loginwithgoogle;
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.support.v7.app.AppCompatActivity;
import Android.support.v7.widget.Toolbar;
import Android.util.Log;
import Android.view.Menu;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.ImageView;
import Android.widget.LinearLayout;
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.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.Android.gms.plus.Plus;
import com.google.Android.gms.plus.model.people.Person;
import Java.io.InputStream;
// A project by Ferdousur Rahman Shajib
// www.androstock.com
public class MainActivity extends AppCompatActivity implements OnClickListener,
GoogleApiClient.ConnectionCallbacks, OnConnectionFailedListener {
// Profile pic image size in pixels
private static final int PROFILE_PIC_SIZE = 400;
/* Request code used to invoke sign in user interactions. */
private static final int RC_SIGN_IN = 0;
/* Client used to interact with Google APIs. */
private GoogleApiClient mGoogleApiClient;
/* A flag indicating that a PendingIntent is in progress and prevents
* us from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mShouldResolve;
private ConnectionResult connectionResult;
private SignInButton signInButton;
private Button signOutButton;
private TextView tvName, tvMail, tvNotSignedIn;
private ImageView imgProfilePic;
private LinearLayout viewContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgProfilePic = (ImageView) findViewById(R.id.imgProfilePic);
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
signOutButton = (Button) findViewById(R.id.sign_out_button);
tvName = (TextView) findViewById(R.id.tvName);
tvMail = (TextView) findViewById(R.id.tvMail);
tvNotSignedIn = (TextView) findViewById(R.id.notSignedIn_tv);
viewContainer = (LinearLayout) findViewById(R.id.text_view_container);
signInButton.setOnClickListener(this);
signOutButton.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.build();
}
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
private void resolveSignInError() {
if (connectionResult.hasResolution()) {
try {
mIntentInProgress = true;
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
/*
When the GoogleApiClient object is unable to establish a connection onConnectionFailed() is called
*/
@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}
if (!mIntentInProgress) {
connectionResult = result;
if (mShouldResolve) {
resolveSignInError();
}
}
}
/*
onConnectionFailed() was started with startIntentSenderForResult and the code RC_SIGN_IN,
we can capture the result inside Activity.onActivityResult.
*/
@Override
protected void onActivityResult(int requestCode, int responseCode,
Intent intent) {
if (requestCode == RC_SIGN_IN) {
if (responseCode != RESULT_OK) {
mShouldResolve = false;
}
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
@Override
public void onConnected(Bundle arg0) {
mShouldResolve = false;
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person person = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
String personName = person.getDisplayName();
String personPhotoUrl = person.getImage().getUrl();
String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
tvName.setText(personName);
tvMail.setText(email);
personPhotoUrl = personPhotoUrl.substring(0,
personPhotoUrl.length() - 2)
+ PROFILE_PIC_SIZE;
new LoadProfileImage(imgProfilePic).execute(personPhotoUrl);
Toast.makeText(getApplicationContext(),
"You are Logged In " + personName, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Couldnt Get the Person Info", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
signOutUI();
}
private void signOutUI() {
signInButton.setVisibility(View.GONE);
tvNotSignedIn.setVisibility(View.GONE);
signOutButton.setVisibility(View.VISIBLE);
viewContainer.setVisibility(View.VISIBLE);
}
private void signInUI() {
signInButton.setVisibility(View.VISIBLE);
tvNotSignedIn.setVisibility(View.VISIBLE);
signOutButton.setVisibility(View.GONE);
viewContainer.setVisibility(View.GONE);
}
/**
* Fetching user's information name, email, profile pic
*/
private void getProfileInformation() {
}
@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
signInUI();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
onSignInClicked();
break;
case R.id.sign_out_button:
onSignOutClicked();
break;
}
}
private void onSignInClicked() {
if (!mGoogleApiClient.isConnecting()) {
mShouldResolve = true;
resolveSignInError();
}
}
private void onSignOutClicked() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
signInUI();
}
}
/**
* 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);
}
}
}
Créez activity_main.xml qui contiendra notre structure de connexion et de déconnexion.
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical"
Android:gravity="center">
<LinearLayout
Android:id="@+id/text_view_container"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:orientation="vertical"
Android:paddingLeft="16dp"
Android:paddingRight="16dp"
Android:visibility="gone"
Android:gravity="center">
<ImageView
Android:id="@+id/imgProfilePic"
Android:layout_width="80dp"
Android:layout_height="wrap_content"/>
<TextView
Android:id="@+id/tvName"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:padding="5dp"
Android:textSize="20dp" />
<TextView
Android:id="@+id/tvMail"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:padding="5dp"
Android:textSize="18dp" />
</LinearLayout>
<Button
Android:id="@+id/sign_out_button"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
Android:layout_marginBottom="10dp"
Android:background="@Android:color/holo_red_light"
Android:layout_marginLeft="19dp"
Android:layout_marginRight="19dp"
Android:text="LOGOUT"
Android:textColor="#fff"
Android:textStyle="bold"
Android:visibility="gone" />
<TextView
Android:id="@+id/notSignedIn_tv"
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:layout_gravity="center_horizontal"
Android:layout_marginBottom="30dp"
Android:text="You are not Signed In"
Android:textSize="20sp" />
<com.google.Android.gms.common.SignInButton
Android:id="@+id/sign_in_button"
Android:layout_width="220dp"
Android:layout_height="wrap_content"
Android:layout_gravity="center_horizontal" />
</LinearLayout>
Thats it les gens. Vous avez terminé avec Google+ Login . Pour plus de détails, vous pouvez visiter ici .
Voici comment j'intègre la connexion Google avec la dernière et la plus fluide des méthodes.
Depuis cette référence: google login Android studio
commencez par créer une application dans la console de développement Google et téléchargez le fichier de configuration, puis copiez-le dans le dossier de l'application.
puis ajoutez ce qui suit dans build.gradle(Project: project_name)
classpath 'com.google.gms:google-services:1.5.0-beta2'
maven { url 'https://jitpack.io' }
allprojects {
repositories {
}
}
ajouter du code dans build.gradle(Module:app)
compile 'com.google.Android.gms:play-services-auth:9.0.2'
compile 'com.google.Android.gms:play-services:9.0.2'
compile 'com.github.androidquery:androidquery:0.26.9'
ajouter ce qui suit dans activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical"
tools:context="com.exampledemo.parsaniahardik.google_login_demonuts.MainActivity">
<ImageView
Android:layout_width="200dp"
Android:layout_height="200dp"
Android:scaleType="fitXY"
Android:layout_marginTop="20dp"
Android:layout_gravity="center_horizontal"
Android:id="@+id/iv"/>
<TextView
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:id="@+id/text"
Android:textColor="#000"
Android:layout_marginTop="20dp"
Android:textAppearance="?android:attr/textAppearanceMedium"/>
<com.google.Android.gms.common.SignInButton
Android:id="@+id/sign_in_button"
Android:layout_width="200dp"
Android:layout_marginTop="20dp"
Android:layout_height="wrap_content"
Android:layout_gravity="center_horizontal" />
<Button
Android:layout_width="200dp"
Android:layout_height="wrap_content"
Android:layout_marginTop="20dp"
Android:layout_gravity="center_horizontal"
Android:text="Logout"
Android:id="@+id/btn"/>
</LinearLayout>
ajouter ci-dessous dans MainActivity.Java
import Android.content.Intent;
import Android.support.annotation.NonNull;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.util.Log;
import Android.view.View;
import Android.widget.Button;
import Android.widget.ImageView;
import Android.widget.TextView;
import Android.widget.Toast;
import com.androidquery.AQuery;
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.SignInButton;
import com.google.Android.gms.common.api.GoogleApiClient;
import com.google.Android.gms.common.api.ResultCallback;
import com.google.Android.gms.common.api.Status;
import com.google.Android.gms.plus.People;
import com.google.Android.gms.plus.Plus;
import com.google.Android.gms.plus.model.people.Person;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener{
private SignInButton signInButton;
private GoogleSignInOptions gso;
private GoogleApiClient mGoogleApiClient;
private int SIGN_IN = 30;
private TextView tv;
private ImageView iv;
private AQuery aQuery;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
signInButton = (SignInButton) findViewById(R.id.sign_in_button);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(Plus.API)
.build();
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, SIGN_IN);
}
});
tv = (TextView) findViewById(R.id.text);
iv = (ImageView) findViewById(R.id.iv);
btn = (Button) findViewById(R.id.btn);
aQuery = new AQuery(this);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
Toast.makeText(MainActivity.this, "Logout Successfully!", Toast.LENGTH_SHORT).show();
}
});
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//If signin
if (requestCode == SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
//Calling a new function to handle signin
handleSignInResult(result);
}
}
private void handleSignInResult(GoogleSignInResult result) {
//If the login succeed
if (result.isSuccess()) {
//Getting google account
final GoogleSignInAccount acct = result.getSignInAccount();
//Displaying name and email
String name = acct.getDisplayName();
final String mail = acct.getEmail();
// String photourl = acct.getPhotoUrl().toString();
final String givenname="",familyname="",displayname="",birthday="";
Plus.PeopleApi.load(mGoogleApiClient, acct.getId()).setResultCallback(new ResultCallback<People.LoadPeopleResult>() {
@Override
public void onResult(@NonNull People.LoadPeopleResult loadPeopleResult) {
Person person = loadPeopleResult.getPersonBuffer().get(0);
Log.d("GivenName ", person.getName().getGivenName());
Log.d("FamilyName ",person.getName().getFamilyName());
Log.d("DisplayName ",person.getDisplayName());
Log.d("gender ", String.valueOf(person.getGender())); //0 = male 1 = female
String gender="";
if(person.getGender() == 0){
gender = "Male";
}else {
gender = "Female";
}
if(person.hasBirthday()){
tv.setText(person.getName().getGivenName()+" \n"+person.getName().getFamilyName()+" \n"+gender+"\n"+person.getBirthday());
}else {
tv.setText(person.getName().getGivenName()+" \n"+person.getName().getFamilyName()+" \n"+gender);
}
aQuery.id(iv).image(acct.getPhotoUrl().toString());
Log.d("Uriddd",acct.getPhotoUrl().toString());
/* Log.d(TAG,"CurrentLocation "+person.getCurrentLocation());
Log.d(TAG,"AboutMe "+person.getAboutMe());*/
// Log.d("Birthday ",person.getBirthday());
// Log.d(TAG,"Image "+person.getImage());
}
});
} else {
//If login fails
Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show();
}
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Bien sûr, vous voudrez peut-être commencer par ceci:
Les sites Web et applications tiers peuvent désormais permettre aux visiteurs de se connecter en utilisant leurs comptes d'utilisateur Google. Connexion fédérée, basée sur l'OpenID standard, libère les utilisateurs de la nécessité de configurer des comptes de connexion distincts pour différents sites Web - et libère les développeurs de sites Web de la tâche de mettre en œuvre des mesures d'authentification de connexion. OpenID y parvient objectif en fournissant un cadre dans lequel les utilisateurs peuvent créer un compte avec un fournisseur OpenID, tel que Google, et utilisez ce compte pour signer dans n'importe quel site Web qui accepte les OpenID. Cette page décrit comment intégrer la connexion fédérée de Google pour un site Web ou une application.
https://developers.google.com/accounts/docs/OpenID
Revenez quand vous êtes coincé!
Vous ne pouvez pas vous connecter exactement à une application Android à l'aide d'un compte Google. Vous utilisez un compte Google pour vous connecter à un site Web ou à un service Web tel que GMail, Agenda, etc., ou à un site Web tiers si vous utilisez OpenID. Étant donné que votre application n'est pas un site Web, cela ne fonctionnera pas. Vous pouvez faire l’un des choix suivants:
AccountManager
) sur son téléphone et ne le laissez utiliser l'application que s'il en a un. Si un compte est enregistré, vous pouvez être raisonnablement sûr qu'ils connaissent le mot de passe (ou qu'ils ont volé le téléphone de quelqu'un ...) **Dependency**
**Need Internet Permission**
**Working Code see Link on Play Store**
https://play.google.com/store/search?q=com.codecube.airbucks
compile 'com.google.Android.gms:play-services:8.3.0'
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:orientation="vertical">
<com.google.Android.gms.common.SignInButton
Android:id="@+id/sign_in_button"
Android:layout_width="200dp"
Android:layout_marginTop="20dp"
Android:layout_height="wrap_content"
Android:layout_gravity="center_horizontal" />
<Button
Android:layout_width="200dp"
Android:layout_height="wrap_content"
Android:layout_marginTop="20dp"
Android:layout_gravity="center_horizontal"
Android:text="Logout"
Android:id="@+id/btn"/>
</LinearLayout>
package com.keshav.geofencing;
import Android.Manifest;
import Android.annotation.TargetApi;
import Android.app.ProgressDialog;
import Android.content.BroadcastReceiver;
import Android.content.Intent;
import Android.content.pm.PackageManager;
import Android.net.Uri;
import Android.os.Build;
import Android.os.Bundle;
import Android.support.v4.app.ActivityCompat;
import Android.support.v4.content.ContextCompat;
import Android.support.v4.content.LocalBroadcastManager;
import Android.support.v7.app.AppCompatActivity;
import Android.util.Log;
import Android.view.View;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.LinearLayout;
import Android.widget.TextView;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.google.Android.gms.appindexing.Action;
import com.google.Android.gms.appindexing.AppIndex;
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.GoogleApiAvailability;
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;
import org.json.JSONException;
import org.json.JSONObject;
import Java.util.Arrays;
import utilities.CommonMethod;
import utilities.LoginPreferences;
public class LoginWithGmail extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "LoginActivity";
private static final int RC_SIGN_IN = 9001;
Button loginSub;
LinearLayout signInButton;
String gmailId;
String gmailName;
String gmailUserEmailId;
Uri gmailUserPhoto;
String savePassword;
LinearLayout btnlogin;
TextView btnsigning;
ProgressDialog prgDialog;
private CallbackManager callbackManager;
private BroadcastReceiver mRegistrationBroadcastReceiver;
private LinearLayout fbloginButton;
// private CallbackManager callbackManager;
private ProgressDialog mProgressDialog;
private GoogleApiClient mGoogleApiClient;
EditText edtEmail;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login1);
checkPermission();
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(AppIndex.API).build();
// Google Sign up Button
signInButton = (LinearLayout) findViewById(R.id.sign_in_button);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this, Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
//showing dialog to select image
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(signInIntent, RC_SIGN_IN);
Log.e("permission", "granted");
} else {
ActivityCompat.requestPermissions(LoginWithGmail.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 1);
}
} else {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
}
});
}
public void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permissionCheck = ContextCompat.checkSelfPermission(LoginWithGmail.this,
Manifest.permission.CAMERA);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
//showing dialog to select image
if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
Log.e("keshav", "Permission if part marsh");
} else {
CommonMethod.showAlert("Internet Connectivity Failure", LoginWithGmail.this);
}
Log.e("keshav", "permission granted");
} else {
ActivityCompat.requestPermissions(LoginWithGmail.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
}
}
@Override
protected void onResume() {
super.onResume();
// LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
// new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
}
@Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
// TODO ADD ME
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.e(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}
// [START signOut]
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
// updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END signOut]
// [START revokeAccess]
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
@Override
public void onResult(Status status) {
// [START_EXCLUDE]
// updateUI(false);
// [END_EXCLUDE]
}
});
}
// [END revokeAccess]
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.e(TAG, "onConnectionFailed:" + connectionResult);
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(true);
}
if (LoginWithGmail.this != null && mProgressDialog != null && !mProgressDialog.equals("null"))
mProgressDialog.show();
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()&& !mProgressDialog.equals("null")) {
mProgressDialog.hide();
}
}
// TODO ADD ME ENd
private void handleSignInResult(GoogleSignInResult result) {
Log.e("&&&s", "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
GoogleSignInAccount acct = result.getSignInAccount();
gmailId = acct.getId();
gmailName = acct.getDisplayName();
gmailUserEmailId = acct.getEmail();
gmailUserPhoto = acct.getPhotoUrl();
Log.e("gmailId", "is -->" + gmailId);
Log.e("gmailName", "is -->" + gmailName);
Log.e("gmailUserEmailId", "is -->" + gmailUserEmailId);
Log.e("gmailUserPhoto", "is -->" + gmailUserPhoto);
LoginPreferences.getActiveInstance(LoginWithGmail.this).setUserName(gmailName);
LoginPreferences.getActiveInstance(LoginWithGmail.this).setProfileImage(""+gmailUserPhoto);
Log.e("information", "using Gmail is > " + gmailId + " " + gmailName + "" + gmailUserEmailId + "" + gmailUserPhoto);
if (CommonMethod.isNetworkAvailable(LoginWithGmail.this)) {
Log.e("SignUp gmail", "Hit API..........................");
Intent i=new Intent(LoginWithGmail.this,DrawerActivity.class);
LoginPreferences.getActiveInstance(LoginWithGmail.this).setIsLoggedIn(true);
startActivity(i);
finish();
// TODO Here Registered User in own Database call Volley Retrofit2 Api ....
new SignUpSocialFacebookAsyncTask().execute();
} else {
CommonMethod.showAlert("Intenet Connectivity Failure", LoginWithGmail.this);
}
} else {
}
// TODO ADD ME KESHAV Google GMail Logout
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Login Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://Host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("Android-app://com.keshav.geofencing/http/Host/path")
);
AppIndex.AppIndexApi.end(mGoogleApiClient, viewAction);
mGoogleApiClient.disconnect();
}
//Todo add new method for permission
@TargetApi(Build.VERSION_CODES.M)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == RC_SIGN_IN) {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
signInIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
}
}
**Dependency**
**Need Internet Permission**
**Working Code see Link on Play Store**
https://play.google.com/store/search?q=com.codecube.airbucks