Tuesday, September 24, 2013

Google account Integration in Android | Login with Gmail | Signup with Google in Android | Get Google Profile photo in Android

Hello Friends,
This is my post for Google account integration with your application,  login with gmail, signup with Google account. Some important step is given below-

Step 1- Create new project say GoogleProfileDemo.
Step 2- Add "Google play service" libray project.
Step 3 - Add needed permission in manifest.xml-

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




1)SplashActivity.java

package com.manish.google.profile;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.auth.GoogleAuthUtil;

/**
 * @author manish
 * 
 */
public class SplashActivity extends Activity {
	Context mContext = SplashActivity.this;
	AccountManager mAccountManager;
	String token;
	int serverCode;
	private static final String SCOPE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Splash screen view
		setContentView(R.layout.activity_splash);
			syncGoogleAccount();
		

	}

	private String[] getAccountNames() {
		mAccountManager = AccountManager.get(this);
		Account[] accounts = mAccountManager
				.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
		String[] names = new String[accounts.length];
		for (int i = 0; i < names.length; i++) {
			names[i] = accounts[i].name;
		}
		return names;
	}

	private AbstractGetNameTask getTask(SplashActivity activity, String email,
			String scope) {
		return new GetNameInForeground(activity, email, scope);

	}

	public void syncGoogleAccount() {
		if (isNetworkAvailable() == true) {
			String[] accountarrs = getAccountNames();
			if (accountarrs.length > 0) {
				//you can set here account for login
				getTask(SplashActivity.this, accountarrs[0], SCOPE).execute();
			} else {
				Toast.makeText(SplashActivity.this, "No Google Account Sync!",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(SplashActivity.this, "No Network Service!",
					Toast.LENGTH_SHORT).show();
		}
	}
	public boolean isNetworkAvailable() {

		ConnectivityManager cm = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = cm.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			Log.e("Network Testing", "***Available***");
			return true;
		}
		Log.e("Network Testing", "***Not Available***");
		return false;
	}
}

2)HomeActivity.java


package com.manish.google.profile;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * @author manish
 * 
 */
public class HomeActivity extends Activity {
	ImageView imageProfile;
	TextView textViewName, textViewEmail, textViewGender, textViewBirthday;
	String textName, textEmail, textGender, textBirthday, userImageUrl;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		imageProfile = (ImageView) findViewById(R.id.imageView1);
		textViewName = (TextView) findViewById(R.id.textViewNameValue);
		textViewEmail = (TextView) findViewById(R.id.textViewEmailValue);
		textViewGender = (TextView) findViewById(R.id.textViewGenderValue);
		textViewBirthday = (TextView) findViewById(R.id.textViewBirthdayValue);

		/**
		 * get user email using intent
		 */

		Intent intent = getIntent();
		textEmail = intent.getStringExtra("email_id");
		System.out.println(textEmail);
		textViewEmail.setText(textEmail);

		/**
		 * get user data from google account
		 */

		try {
			System.out.println("On Home Page***"
					+ AbstractGetNameTask.GOOGLE_USER_DATA);
			JSONObject profileData = new JSONObject(
					AbstractGetNameTask.GOOGLE_USER_DATA);

			if (profileData.has("picture")) {
				userImageUrl = profileData.getString("picture");
				new GetImageFromUrl().execute(userImageUrl);
			}
			if (profileData.has("name")) {
				textName = profileData.getString("name");
				textViewName.setText(textName);
			}
			if (profileData.has("gender")) {
				textGender = profileData.getString("gender");
				textViewGender.setText(textGender);
			}
			if (profileData.has("birthday")) {
				textBirthday = profileData.getString("birthday");
				textViewBirthday.setText(textBirthday);
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... urls) {
			Bitmap map = null;
			for (String url : urls) {
				map = downloadImage(url);
			}
			return map;
		}

		// Sets the Bitmap returned by doInBackground
		@Override
		protected void onPostExecute(Bitmap result) {
			imageProfile.setImageBitmap(result);
		}

		// Creates Bitmap from InputStream and returns it
		private Bitmap downloadImage(String url) {
			Bitmap bitmap = null;
			InputStream stream = null;
			BitmapFactory.Options bmOptions = new BitmapFactory.Options();
			bmOptions.inSampleSize = 1;

			try {
				stream = getHttpConnection(url);
				bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
				stream.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			return bitmap;
		}

		// Makes HttpURLConnection and returns InputStream
		private InputStream getHttpConnection(String urlString)
				throws IOException {
			InputStream stream = null;
			URL url = new URL(urlString);
			URLConnection connection = url.openConnection();

			try {
				HttpURLConnection httpConnection = (HttpURLConnection) connection;
				httpConnection.setRequestMethod("GET");
				httpConnection.connect();

				if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
					stream = httpConnection.getInputStream();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return stream;
		}
	}
}

3)AbstractGetNameTask.java


/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.manish.google.profile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;

import com.google.android.gms.auth.GoogleAuthUtil;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

/**
 * Display personalized greeting. This class contains boilerplate code to
 * consume the token but isn't integral to getting the tokens.
 */
public abstract class AbstractGetNameTask extends AsyncTask<Void, Void, Void> {
	private static final String TAG = "TokenInfoTask";
	protected SplashActivity mActivity;
   public static String GOOGLE_USER_DATA="No_data";
	protected String mScope;
	protected String mEmail;
	protected int mRequestCode;

	AbstractGetNameTask(SplashActivity activity, String email, String scope) {
		this.mActivity = activity;
		this.mScope = scope;
		this.mEmail = email;
	}

	@Override
	protected Void doInBackground(Void... params) {
		try {
			fetchNameFromProfileServer();
			
		} catch (IOException ex) {
			onError("Following Error occured, please try again. "
					+ ex.getMessage(), ex);
		} catch (JSONException e) {
			onError("Bad response: " + e.getMessage(), e);
		}
		return null;
	}

	protected void onError(String msg, Exception e) {
		if (e != null) {
			Log.e(TAG, "Exception: ", e);
		}
	}

	/**
	 * Get a authentication token if one is not available. If the error is not
	 * recoverable then it displays the error message on parent activity.
	 */
	protected abstract String fetchToken() throws IOException;

	/**
	 * Contacts the user info server to get the profile of the user and extracts
	 * the first name of the user from the profile. In order to authenticate
	 * with the user info server the method first fetches an access token from
	 * Google Play services.
	 * @return 
	 * @return 
	 * 
	 * @throws IOException
	 *             if communication with user info server failed.
	 * @throws JSONException
	 *             if the response from the server could not be parsed.
	 */
	private void fetchNameFromProfileServer() throws IOException, JSONException {
		String token = fetchToken();
		URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+ token);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		int sc = con.getResponseCode();
		if (sc == 200) {
			InputStream is = con.getInputStream();
			GOOGLE_USER_DATA = readResponse(is);
			is.close();
			
			Intent intent=new Intent(mActivity,HomeActivity.class);
			intent.putExtra("email_id", mEmail);
			mActivity.startActivity(intent);
			mActivity.finish();
			return;
		} else if (sc == 401) {
			GoogleAuthUtil.invalidateToken(mActivity, token);
			onError("Server auth error, please try again.", null);
			//Toast.makeText(mActivity, "Please try again", Toast.LENGTH_SHORT).show();
			//mActivity.finish();
			return;
		} else {
			onError("Server returned the following error code: " + sc, null);
			return;
		}
	}

	/**
	 * Reads the response from the input stream and returns it as a string.
	 */
	private static String readResponse(InputStream is) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] data = new byte[2048];
		int len = 0;
		while ((len = is.read(data, 0, data.length)) >= 0) {
			bos.write(data, 0, len);
		}
		return new String(bos.toByteArray(), "UTF-8");
	}

	
}

4)GetNameInForeground.java


/*
 * Copyright 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.manish.google.profile;

import java.io.IOException;

import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
import com.google.android.gms.auth.UserRecoverableAuthException;

/**
 * This example shows how to fetch tokens if you are creating a foreground task/activity and handle
 * auth exceptions.
 */
public class GetNameInForeground extends AbstractGetNameTask {

  public GetNameInForeground(SplashActivity activity, String email, String scope) {
      super(activity, email, scope);
  }


  /**
   * Get a authentication token if one is not available. If the error is not recoverable then
   * it displays the error message on parent activity right away.
   */
  @Override
  protected String fetchToken() throws IOException {
      try {
          return GoogleAuthUtil.getToken(mActivity, mEmail, mScope);
      } catch (GooglePlayServicesAvailabilityException playEx) {
          // GooglePlayServices.apk is either old, disabled, or not present.
      } catch (UserRecoverableAuthException userRecoverableException) {
          // Unable to authenticate, but the user can fix this.
          // Forward the user to the appropriate activity.
          mActivity.startActivityForResult(userRecoverableException.getIntent(), mRequestCode);
      } catch (GoogleAuthException fatalException) {
          onError("Unrecoverable error " + fatalException.getMessage(), fatalException);
      }
      return null;
  }
}

5)activity_splash.xml


<RelativeLayout 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"
    tools:context=".SplashActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Please wait..."
        android:textSize="25sp" />

    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:text="By:Manish Srivastava" />

</RelativeLayout>

6)activity_home.xml


<RelativeLayout 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:layout_margin="7dp" >

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="Home Page"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/textViewNameLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textViewTitle"
        android:layout_marginTop="15dp"
        android:text="Name:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewNameValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textViewTitle"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/textViewNameLabel"
        android:text="Name:"
        android:textSize="18sp" />
    
      <TextView
        android:id="@+id/textViewEmailLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewNameLabel"
        android:layout_marginTop="15dp"
        android:text="Email:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewEmailValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textViewNameValue"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="15dp"
        android:layout_toRightOf="@id/textViewEmailLabel"
        android:text="Email:"
        android:textSize="18sp" />
    
     <TextView
        android:id="@+id/textViewGenderLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewEmailLabel"
        android:layout_marginTop="15dp"
        android:text="Gender:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewGenderValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/textViewGenderLabel"
        android:layout_alignLeft="@+id/textViewNameValue"
        android:text="Gender:"
        android:textSize="18sp" />
    
     <TextView
        android:id="@+id/textViewBirthdayLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/textViewGenderLabel"
        android:layout_marginTop="15dp"
        android:text="Birthday:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/textViewBirthdayValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textViewBirthdayLabel"
        android:layout_alignBottom="@+id/textViewBirthdayLabel"
        android:layout_toRightOf="@+id/textViewBirthdayLabel"
        android:text="Birthday:"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@+id/textViewTitle"/>
   
</RelativeLayout>

7)AndroidManifest.xml


<manifest android:versioncode="1" android:versionname="1.0" package="com.manish.google.profile" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk android:minsdkversion="8" android:targetsdkversion="16">

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

    <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:label="@string/app_name" android:name="com.manish.google.profile.SplashActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
        <activity android:name="com.manish.google.profile.HomeActivity">
    </activity></application>

</uses-permission></uses-permission></uses-permission></uses-permission></uses-permission></uses-sdk></manifest>

Download Zip Code


Please post your feedback :)
Thanks!



109 comments:

  1. Can you upload test project to github?

    ReplyDelete
    Replies
    1. Sure dear today I will upload, please check after some time.

      Delete
    2. Hi Please download the zip code from git server-
      https://github.com/manishsri01/GoogleProfileDemo.git

      Delete
    3. i am not able to redirect on my app when i ist time rum my app with this code but second time am go to my second screen after successfull login,could you tell me what will be the prob?

      Delete
    4. @jarnail please see this class-AbstractGetNameTask.java here we hit Google server for user authentication so if it is successes it give us code 200 and we redirect to next page but in case of 401 it did nothing so you can set any toast or alert dialog for try again.
      well still i did not able to get why Google did not give us response in first time. its working great in second attempt.

      Delete
    5. Yes, its working great in second time.

      Delete
  2. Hi All Please Download the zip code from git server and save your life :)

    https://github.com/manishsri01/GoogleProfileDemo.git

    ReplyDelete
  3. hey ..u r project is not running in my workspace...only loader is going?
    what is problem?

    ReplyDelete
    Replies
    1. in first attempt sometime google did not give us image. so please try ones more time and see your log cat. it should work. It is tested demo and working for me, you can check screen shot.

      Delete
  4. hello, manish your project is not working only splash page open.............loaader is running.......

    ReplyDelete
    Replies
    1. in first attempt sometime google did not give us image. so please try ones more time and see your log cat. it should work. It is tested demo and working for me, you can check screen shot.

      Delete
    2. i already try many time but not work .......

      Delete
  5. "No Google Account Sync! this toast msg come every time when i run program

    ReplyDelete
    Replies
    1. ohhh dear i got it.. where are you tested mobile phone or on emulator? please test it on mobile device.
      And plese see log cat what error you are getting? code 400 or 200? please reply...

      Delete
    2. And yes one more thing please check have you sync any google account with your mobile phone or not..
      and please check net connectivity too.

      Delete
    3. i hve tried it on phone also...but it is getting unfortunately stooped..PLZ help....

      Delete
  6. how can i remove "view basic information about your account" button from screen.
    Please help

    ReplyDelete
    Replies
    1. no no you can't this is google default page. you can't make any change normally.

      Delete
    2. for first time when i integrate it it not shown any details like email ect. But after restarting an app it shows the data like email, gender.

      Delete
    3. yes you are right. I am also surprise why not google give us 404 error means no data..
      But its working any how :)

      Delete
  7. only loader is loading both in emulator and mobile,can u please tell me what can be the issue

    ReplyDelete
    Replies
    1. 1)have you tried second time?
      2)is your device sync with any Google account?
      3)is internet is available there?

      if these things is okay it should work.

      Delete
  8. yes my account is synchronized,internet is availble

    ReplyDelete
    Replies
    1. and what about 1)have you tried second time?
      if everything okay it should work. if still you are facing issue please use debuger and let me know response from google server.

      Thanks!

      Delete
  9. your tutorial very useful.
    Can u tell me how to save username and password into database by using account manager.

    ReplyDelete
  10. Very Nice tutorial indeed.Have you figured out the reason of not getting details the first time we launch app and works fine the second time? There must be some reason to it.Kindly reply.

    ReplyDelete
    Replies
    1. still i did not check, i think this problem from google side not from developer. may be a new update available now on google please check for google update.

      Delete
  11. I have downloaded your project i am getting error at

    import com.google.android.gms.auth.GoogleAuthException;
    import com.google.android.gms.auth.GoogleAuthUtil;
    import com.google.android.gms.auth.GooglePlayServicesAvailabilityException;
    import com.google.android.gms.auth.UserRecoverableAuthException;

    i am new to android so please suggest me about the error..

    ReplyDelete
    Replies
    1. i think you did not add google play store libray in your project. if it is not here please add it..

      Delete
  12. i have added the google-play service library but it still shows errorr new to android plz reply

    ReplyDelete
    Replies
    1. what error you are getting? same above error? please ones clean and rebuild your project.

      Delete
  13. I am a beginner of few days...I am little confused,i am using oauth 2.0 ,there is no mentn of client id and client secret in your code where would i put my client id and secret do i put in the scope url or in the HttpConnection url plz help me out!!!!

    ReplyDelete
    Replies
    1. There is no need of oauth. It will work with all application.

      Delete
  14. How did you ..solved the google play service out of date problem... on which version of google api and google play service you worked on..name the versions plzzzzz.. with revision s plzz if u had cracked it plz let me knowww

    ReplyDelete
    Replies
    1. when I was publish this post i was using old play services version(API level-18) I don't know version name but now I am using new one with API level-22. Any issue here?

      Delete
  15. Hello friend how can i get all email to select one to sync..

    ReplyDelete
    Replies
    1. Hi Shanmuga, from where you want all email to sync? from your gmail account ?

      Delete
  16. Hello Manish if i click sigin in button means which shows all email and then select any one to sync please help

    ReplyDelete
    Replies
    1. It is not simple well if you want you can see here-

      private String[] getAccountNames() {
      mAccountManager = AccountManager.get(this);
      Account[] accounts = mAccountManager .getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE); String[] names = new String[accounts.length];
      for (int i = 0; i < names.length; i++)
      { names[i] = accounts[i].name;
      }
      return names;
      }

      Here I am getting all list of account and used only 0th potion so you can put them in a list or popup for choose to user and then pass the selected potion.

      Delete
  17. Hello Manish Thanks for your answer please tell how to show in list or pop up please help and how to sign out also? Thanks

    ReplyDelete
    Replies
    1. Hello dear,

      I always try to help to my followers but problem is that I have to do my work too parallel. So I can't write code for everyone for all problems.

      So do one thing just start with a demo project and try at your end. All demo's and code available on my blog and others blogger's blog just follow them. Like create a popup with list of google account etc. If you got stuck any point ask me know issue. Sure I will help you but not whole app any one do for you.

      Please don't mind but it is fact, a lot of people on my blog and they want I provide all code related to their project but please think from my place is it possible dear to write code for everyone?

      I know you are good in coding and you always read my all post and promote them but everyone have a limited time. Please don't think me wrong, I am your's friend and always here for help but thing is that just do some self effort if you face any problem I will try to short out.

      Thanks!

      Delete
  18. Hi manish please how to log out from google plus in different activity....Thanks

    ReplyDelete
  19. Hi manish once synced google means how to remove the account please tell...

    ReplyDelete
    Replies
    1. Sorry dear for late reply. You can give a log-out button inside your application and when user logout ones send him to out on main page and if again want login into app he have to press login button. And there is no option for logout session from app of google account in my knowledge. And I have never seen any app like this.

      Delete
  20. Hello...u r project is not running . If we run this project splash screen is loading after few second application is forced close . what is problem?

    ReplyDelete
  21. Today I have run this project it is running . But profile image and date of birth is not display. What is problem?

    ReplyDelete
  22. Hello dear,
    It shows error while launching on my device..


    A required meta-data tag in your app's AndroidManifest.xml does not exist. You must have the following declaration within the element:

    ReplyDelete
  23. Hello I get only "Please wait " screen. not able to move ahead. I got Email address in Log. then can't move ahead and tokan is null

    ReplyDelete
  24. Activity com.manish.googleprofiledemo.SplashActivity has leaked ServiceConnection com.google.android.gms.internal.h@40d19a78 that was originally bound here

    ReplyDelete
  25. can we get the click of ok button in google authentication alert view?

    ReplyDelete
  26. i got the solution for the demo and i am going to put over here or on the any other opensource platform.

    ReplyDelete
  27. hi manish,
    you have any blog or source and tutorial for google plus or twitter for android...? please help me.

    ReplyDelete
  28. Is there any way to Login with Google Account without use of Google Play Services library?

    ReplyDelete
    Replies
    1. No dear in my knowledge there is no way. Please check on google. May be they provide Google API's.

      Delete
  29. Hi Manish,
    You have any source for getting Gmail contacts list with standard authentication

    ReplyDelete
    Replies
    1. Hi Manish, The above code is not giving Date of birth, This is giving the profileData.has("birthday") is False. Can you give any suggestion to fetching my birthday as well as my friends birthday who are there in my Google Circle. .. :) (Note i kept my birthday Scope is Public only)

      Delete
  30. Hi manish .Here I am unable to go next screen.It's keep on executing do in background with dialog.what cai i do?plaese reply

    ReplyDelete
    Replies
    1. Hey, It should work. May be in first time it will not work but in second time it should work.
      Please check log-cat is there any info or error?

      Delete
  31. Hi,
    I am using DremWeaver to make applications with PhoneGap and not have any file AndroidManifest.xml or other...

    How can adapt your code to make it work for me?

    Thank you very much in advance

    ReplyDelete
    Replies
    1. You can't use Android library and code in your phoneGap application. Better way use Java-Script or read Google doc.

      Delete
  32. great tutorials every thing is work perfect fine .thanks

    ReplyDelete
  33. hiii can u tell how to get contact name and password of gmail.

    ReplyDelete
    Replies
    1. So you want hack some one account :), might be mine:) :)
      You can't dear. Google allow us to get only basic public info of any user.

      Delete
  34. I'm having error given below :
    Please suggest me the solution...

    05-21 12:28:31.006: E/AndroidRuntime(9420): java.lang.VerifyError: com/manish/googleprofiledemo/GetNameInForeground
    05-21 12:28:31.006: E/AndroidRuntime(9420): at com.manish.googleprofiledemo.SplashActivity.getTask(SplashActivity.java:50)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at com.manish.googleprofiledemo.SplashActivity.syncGoogleAccount(SplashActivity.java:59)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at com.manish.googleprofiledemo.SplashActivity.onCreate(SplashActivity.java:32)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.Activity.performCreate(Activity.java:5104)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.ActivityThread.access$600(ActivityThread.java:141)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.os.Handler.dispatchMessage(Handler.java:99)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.os.Looper.loop(Looper.java:137)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at android.app.ActivityThread.main(ActivityThread.java:5041)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at java.lang.reflect.Method.invokeNative(Native Method)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at java.lang.reflect.Method.invoke(Method.java:511)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    05-21 12:28:31.006: E/AndroidRuntime(9420): at dalvik.system.NativeStart.main(Native Method)

    ReplyDelete
  35. where you used client id in it. i am not able to find this in your code???

    ReplyDelete
  36. Thanks for Gmail integration and i want to logout in my application

    ReplyDelete
    Replies
    1. N case of google login just give a button for logout inside your app and finish all the activity and set flag clear top. You can redirect on login page again, this is the way in my knowladge. Or you need to sign off from android device from that google account.

      Delete
    2. Which flag n in which activity should i clear n could u please reply the logout button code....

      Delete
    3. btnLogout.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
      // TODO Auto-generated method stub
      Intent intent=new Intent(YourActivity.this,LoginActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      finish();
      }
      });

      Delete
  37. I've imported your project and when I run it in my phone or tablet it says "googleprofiledemo has stopped unexpectedly...". Do you know what's the problem?
    Thanks in advance.

    ReplyDelete
  38. Hello Manish,I did Debugger also.. Am getting force close while run it on mobile device.. My internet is on.. My Google account also in sync... bt not getting output.. This sceen: Please wait... Loading coming for a while and automatically application stopped Please give me a Solution

    ReplyDelete
    Replies
    1. Can you please share your crash report?

      Delete
    2. we face same problem on my Xperia Phone

      Delete
    3. GoogleProfileDemo [Android Application]
      DalvikVM[localhost:8600]
      Thread [<1> main] (Running)
      Thread [<10> Binder_2] (Running)
      Thread [<9> Binder_1] (Running)
      Thread [<11> AsyncTask #1] (Suspended (exception RuntimeException))

      ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: 1130
      ThreadPoolExecutor$Worker.run() line: 587
      Thread.run() line: 841
      Thread [<12> AsyncTask #2] (Running)
      Thread [<13> Binder_3] (Running)
      Thread [<14> Binder_4] (Running)

      Delete
  39. your code is not running on my pc please help me

    ReplyDelete
  40. Hi manish, this code is force close on my sony xperia z phone. please help me.

    ReplyDelete
    Replies
    1. You need to use asynck task instead of direct ui thread.

      Delete
  41. Thank you so much sir for gmail integration....I want to view my all gmail contacts in list view and block any of them by simply clicking on button...is this possible???

    ReplyDelete
    Replies
    1. I think you can't, just Google provide some basic info like name,pic etc.

      Delete
    2. If u get any information regarding this, will u able to acknowledge me?? Its my internship assignment....Plzz :)

      Delete
  42. Hi Manish,

    Thanks its really helpful to get google profile. While fetching profile data not able to get birthday from json response. Birthday tag itself its not there in json response.

    ReplyDelete
  43. how can i make it run in emulator please say

    ReplyDelete
  44. Hi Manish,
    i can't get birthday date. please help with me.

    ReplyDelete
    Replies
    1. Can you check the user detail on Google, is he set his birthday there or not? Anyway if there is any issue check the Google doc. I am not sure about this issue.

      Delete
  45. hi manish u r project is not running only loader is going?

    ReplyDelete
  46. getting "userRecoverableException" each time !

    ReplyDelete
    Replies
    1. I can't say anything with out debug your code. BTW be sure your emulator/phone have Google account and play services? and if everything is fine then check updated Google document may be they changed the process to do things.

      Delete
  47. Hi, i'm using your tutorial and i was just wondering. when you say I should be logged into my gmail, did you mean from a browser login in my mobile or it works with the gmail account installed from playstore? Please reply!

    ReplyDelete
    Replies
    1. Sorry for late reply, gmail login means login into you application using google account like you Facebook, Twitter login.

      Delete
  48. 10-05 05:02:48.163 24699-24699/? D/dalvikvm: Late-enabling CheckJNI
    10-05 05:02:48.323 24699-24699/com.example.root.manishgoogle E/Network Testing: ***Available***
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: : EGL 1.4 QUALCOMM build: LNXBUILD_Nondeterministic_AU+PATCH[ES]_msm8226_LNX.LA.3.5.1_RB1_CL3304448_release_ENGG (CL3304448)
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: OpenGL ES Shader Compiler Version: E031.24.00.14
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: Build Date: 04/21/14 Mon
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: Local Branch:
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: Remote Branch: quic/LNX.LA.3.5.1_RB1.1
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: Local Patches: a27ebf3082ec33cb1a482d04eecdc413bab8c375 Merge "Merge 86ebf3109226685a03c5fa4dcc28577bfa197568 on remote branch"
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL: 7420b63106a370e529e482fdd573206fe0ea20fc Merge 86ebf3109226685a03c5fa4dcc28577bfa197568 on remote branch
    10-05 05:02:48.373 24699-24699/com.example.root.manishgoogle I/Adreno-EGL:
    10-05 05:02:48.423 24699-24699/com.example.root.manishgoogle D/OpenGLRenderer: Enabling debug mode 0
    hi manish this is my log cat pleaase help...

    ReplyDelete
    Replies
    1. I don't know why but Google API have some bug and in first attempt they did not provide any data. Need check it again if Google have been updated their API.

      Delete
  49. This comment has been removed by the author.

    ReplyDelete
  50. I used the following code for getting user information from Google plus, but it sometimes returns null fetchToken() . Please tell me what is wrong in this or suggest another code.

    private void fetchNameFromProfileServer() throws IOException, JSONException {
    String token = fetchToken();
    URL url = new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+token);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    int sc = con.getResponseCode();
    if (sc == 200) {
    InputStream is = con.getInputStream();
    GOOGLE_USER_DATA = readResponse(is);
    is.close();
    System.out.println("Vr: In fetchNameFromProfileServer() of AbstractGetNameTask aync task.");
    mActivity.finish();
    Intent intent=new Intent(mActivity,Profile_Activity.class);
    intent.putExtra("email_id", mEmail);
    mActivity.startActivity(intent);
    mActivity.finish();
    return;
    } else if (sc == 401) {
    GoogleAuthUtil.invalidateToken(mActivity, token);
    onError("Server auth error, please try again.", null);

    return;
    } else {
    onError("Server returned the following error code: " + sc, null);
    return;
    }
    }

    private static String readResponse(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] data = new byte[2048];
    int len = 0;
    while ((len = is.read(data, 0, data.length)) >= 0) {
    bos.write(data, 0, len);
    }
    return new String(bos.toByteArray(), "UTF-8");
    }

    ReplyDelete
    Replies
    1. I don't know why but Google API have some bug and in first attempt they did not provide any data. Need check it again if Google have been updated their API.

      Please check Google developer blog for updated code.

      Delete
  51. how did i know the particular person login with my app.

    ReplyDelete
    Replies
    1. You will get the email-id of the person and you can match it with your database.

      Delete
  52. sir,how to login and send mail in this code

    ReplyDelete
    Replies
    1. you can't send email without user interaction because of user privacy.

      Delete
  53. Logcat:
    04-07 20:11:53.177 10281-10281/? I/art: Late-enabling -Xcheck:jni
    04-07 20:11:53.251 10281-10281/com.example.venka.glogin W/System: ClassLoader referenced unknown path: /data/app/com.example.venka.glogin-1/lib/arm
    04-07 20:11:53.276 10281-10281/com.example.venka.glogin I/GMPM: App measurement is starting up, version: 8487
    04-07 20:11:53.276 10281-10281/com.example.venka.glogin I/GMPM: To enable debug logging run: adb shell setprop log.tag.GMPM VERBOSE
    04-07 20:11:53.282 10281-10281/com.example.venka.glogin E/GMPM: GoogleService failed to initialize, status: 10, Missing an expected resource: 'R.string.google_app_id' for initializing Google services. Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin.
    04-07 20:11:53.283 10281-10281/com.example.venka.glogin E/GMPM: Scheduler not set. Not logging error/warn.
    04-07 20:11:53.297 10281-10316/com.example.venka.glogin E/GMPM: Uploading is not possible. App measurement disabled
    04-07 20:11:53.376 10281-10281/com.example.venka.glogin E/Network Testing: ***Available***
    04-07 20:11:53.395 10281-10321/com.example.venka.glogin D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
    04-07 20:11:53.441 10281-10321/com.example.venka.glogin I/Adreno-EGL: : QUALCOMM Build: 10/21/15, 369a2ea, I96aee987eb
    04-07 20:11:53.443 10281-10321/com.example.venka.glogin I/OpenGLRenderer: Initialized EGL, version 1.4
    04-07 20:11:53.585 10281-10321/com.example.venka.glogin V/RenderScript: 0xb36d8000 Launching thread(s), CPUs 4

    Hello sir im getting the splash screen with no googlesync toast and i had run this app on my nexus device.. so can u please provide me a solution about this?

    ReplyDelete
    Replies
    1. Are you using emulator or real device for testing? Is your phone have google account sync into your phone? its seem you are using emulator or your phone don't have any google account sync.

      Delete
    2. Im working on phone and auto sync is on! yet it shows no googlesync

      Delete
    3. Then you need to google or ask your question on stackoverflow may be someone had same issue.

      Delete
  54. This comment has been removed by the author.

    ReplyDelete