Androidでアプリケーションを開発していますが、ユーザーがGoogleアカウントでログインできるようにしたいのですが、どうすればよいですか?
一部のアプリのように、デバイスで既に構成されているGoogleアカウントのいずれかを使用してユーザーを認証することもできます。そのためには、以下のリンクをクリックしてください-
「OAuth2サービスへの認証」- http://developer.Android.com/training/id-auth/authenticate.html
Googleからサンプルをダウンロード-Android SDK Manager/Extras/Google Play Services
簡単な手順で
これは、プロセスの説明に役立つ別のリンクです- http://Android-developers.blogspot.in/2013/01/verifying-back-end-calls-from-Android.html
アプリにログインする手順は次のとおりです。
以下は、上記の「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"
}
必要に応じてEmail idとその応答を変更する必要があります
SCOPE = "oauth2: https://www.googleapis.com/auth/userinfo.profile ";
に
SCOPE = "oauth2: https://www.googleapis.com/auth/userinfo.profilehttps://www.googleapis.com/auth/userinfo.email " ;
そのサンプルで
http://developer.Android.com/training/id-auth/index.html をご覧ください。アカウントマネージャーの使用方法に関するチュートリアルがあります。 (より具体的には http://developer.Android.com/reference/Android/accounts/AccountManager.html )
まず、build.gradleの依存関係に次の行を挿入します
compile 'com.google.Android.gms:play-services:7.5.0'
ここで、Google Developers Consoleで提供する必要があるSHA-1フィンガープリントが必要です。
Java keytoolは、SHA-1フィンガープリントを生成するために使用されます。コマンドプロンプトを開きます[C:\ Program Files\Java\jdk\binを開いてからShift +右クリック]を押し、次のコマンドを実行してSHA-1指紋を生成し、パスワードにAndroid ifプロンプトが表示されます。
keytool -list -v -keystore "%USERPROFILE%\.Android\debug.keystore" -alias androiddebugkey -storepass Android -keypass Android
Google+ APIを認証して通信するには、Google + APIを有効にし、OAuth 2.0クライアントIDを作成する必要があるGoogle Developers Consoleプロジェクトを作成する必要があります。
ここで、メインフェストファイルへのアクセス許可を宣言します。これは、メタデータとすべての権限を追加した後のマニフェストファイルの外観です。
<?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>
ここで、MainActivity.Javaクラスに向かいます。ここでは、Google +ログインのすべての作業を行います。
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);
}
}
}
ログインおよびログアウトレイアウトを含むactivity_main.xmlを作成します。
<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>
それは人々です。 Google+ログインが完了しました。詳細については、 こちら をご覧ください。
Googleログインと最新かつ最もスムーズな方法を統合する方法を次に示します。
このリファレンスから: google login Android studio
最初にGoogleデベロッパーコンソールでアプリを作成し、設定ファイルをダウンロードしてアプリフォルダーにコピーします。
次に、build.gradle(Project: project_name)
に以下を追加します
_classpath 'com.google.gms:google-services:1.5.0-beta2'
maven { url 'https://jitpack.io' }
allprojects {
repositories {
}
}
_
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'
_
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>
_
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) {
}
}
_
確かにあなたはこれから始めたいかもしれません:
サードパーティのWebサイトおよびアプリケーションでは、訪問者がGoogleユーザーアカウントを使用してサインインできるようになりました。 OpenID標準に基づくフェデレーションログインにより、ユーザーはさまざまなWebサイトに個別のログインアカウントを設定する必要がなくなり、Webサイト開発者はログイン認証手段を実装するタスクから解放されます。 OpenIDは、ユーザーがGoogleなどのOpenIDプロバイダーでアカウントを確立し、そのアカウントを使用してOpenIDを受け入れるWebサイトにサインインできるフレームワークを提供することにより、この目標を達成します。このページでは、GoogleのフェデレーションログインをWebサイトまたはアプリケーションに統合する方法について説明します。
https://developers.google.com/accounts/docs/OpenID
立ち往生したら戻ってきてください!
Googleアカウントを使用してAndroidアプリケーションに正確にログインすることはできません。Googleアカウントを使用して、GMail、カレンダーなど、またはサードパーティなどのWebサイトまたはWebサービスにログインしますOpenIDを使用している場合は、Webサイト(アプリはWebサイトではないため、これは機能しません。次のいずれかを実行できます。
AccountManager
を使用して)登録しているかどうかを確認し、アカウントがある場合のみアプリの使用を許可します。アカウントが登録されている場合、あなたは彼らがパスワードを知っていることを合理的に確信することができます(または誰かの電話を盗んだ...) **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