gmail账户

你好朋友,

这是我的文章,内容是Google帐户与您的应用程序集成,使用gmail登录,使用Google帐户注册。 以下是一些重要的步骤-

  • 第1步-创建一个新项目,例如GoogleProfileDemo。
  • 步骤2-添加“ Google play服务” libray项目。
  • 步骤3 –在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. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// Splash screen viewsetContentView(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 logingetTask(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;@Overridepublic 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 blocke.printStackTrace();}}public class GetImageFromUrl extends AsyncTask<String, Void, Bitmap> {@Overrideprotected Bitmap doInBackground(String... urls) {Bitmap map = null;for (String url : urls) {map = downloadImage(url);}return map;}// Sets the Bitmap returned by doInBackground@Overrideprotected void onPostExecute(Bitmap result) {imageProfile.setImageBitmap(result);}// Creates Bitmap from InputStream and returns itprivate 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 InputStreamprivate 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;}@Overrideprotected 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.*/@Overrideprotected 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" ><TextViewandroid: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" /><ProgressBarandroid: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" /><TextViewandroid: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" ><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><TextViewandroid: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" /><ImageViewandroid: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>
参考: Android中的Google帐户集成–在您博客的Android Hub 4上从我们的JCG合作伙伴 Manish Srivastava 使用Gmail登录 。

翻译自: https://www.javacodegeeks.com/2013/10/google-account-integration-in-android-login-with-gmail.html

gmail账户

gmail账户_Android中的Google帐户集成–使用Gmail登录相关推荐

  1. 如何保护您的Gmail和Google帐户的安全

    Out of all your online accounts, there's a good chance that Google holds most of your information. T ...

  2. 谷歌账户无法添加_如何将另一个Google帐户添加到您的Android设备

    谷歌账户无法添加 In order to set up an Android device, you have to sign in with a Google account. But you ca ...

  3. 谷歌多账户登陆_如何一次登录多个Google帐户

    谷歌多账户登陆 Google has carefully designed its account system so that it can be at the center of your dig ...

  4. 谷歌浏览器 设置多账户_使用多个Google帐户时如何设置默认帐户?

    谷歌浏览器 设置多账户 If you're using multiple Google accounts simultaneously there's a good chance that one o ...

  5. 谷歌账户在别的网上登过_如何在Google帐户之间转移联系人

    谷歌账户在别的网上登过 Google provides no way to automatically sync contacts between two different Google accou ...

  6. 谷歌账户二次验证_为您的Google帐户和Microsoft帐户设置双重身份验证

    谷歌账户二次验证 I use Two-Factor Authentication for my Google Apps account and I use the Google Authenticat ...

  7. 谷歌账户无法添加_如何将多个Google帐户添加到Google Home

    谷歌账户无法添加 Google Home is designed to be a shared device that everyone in the house can use. Now, Goog ...

  8. 解决极值中的神奇设k法_神奇宝贝Go拥有对您的Google帐户的完全访问权限。 这是解决方法[更新]...

    解决极值中的神奇设k法 To say Pokémon GO is wildly popular would be a vast understatement. To say the app's use ...

  9. windows10计算机管理中没有账户,win10系统没有管理员帐户的解决方法

    很多小伙伴都遇到过win10系统没有管理员帐户的情况,想必大家都遇到过win10系统没有管理员帐户的情况吧,那么应该怎么处理win10系统没有管理员帐户呢?我们依照步骤一:确认只有Win10内置管理员 ...

最新文章

  1. 【算法】弗洛伊德(Floyd)算法
  2. 我眼中的Visual Studio 2010架构工具
  3. ELK菜鸟手记 (三) - X-Pack权限控制之给Kibana加上登录控制以及index_not_found_exception问题解决
  4. poj1655Multiplication Puzzle
  5. 如何在关闭ssh连接的情况下,让进程继续运行?
  6. Hive常见的存储格式文件比较
  7. SpringBoot2.X (2)- 使用Spring Initializer 快速创建项目
  8. Python使用模块中对象的几种方法
  9. 1036 和奥巴马一起学编程
  10. 免费小说网站源码 主题XSnov WordPress主题
  11. 神来之笔--图解JVM内存分配及对象存储
  12. 怎么做照片拼图?这些方法值得收藏
  13. JS 实现数字转罗马数字
  14. 创业6年,估值$750亿!张一鸣:人才不是核心竞争力,机制才是!
  15. 因为热爱 全力以赴 心怀远方 定有所成
  16. V型反弹的名场面,荣耀能否在海外市场“荣耀”?
  17. HTML 转 PDf 方法一 wkhtmltopdf.exe
  18. 【基础】银行间市场金融设施
  19. 【差分约束系统】【强连通分量缩点】【拓扑排序】【DAG最短路】CDOJ1638 红藕香残玉簟秋,轻解罗裳,独上兰舟。...
  20. Eclipse怎么离线安装JD-Eclipse反编译插件

热门文章

  1. 西少爷肉夹馍:我们依然是一家互联网公司
  2. rabbitmq 您与此网站的连接不是私密连接
  3. javascript和php中的正则
  4. 怀旧服最新服务器消息,剑网三怀旧服:服务器排队人数2000,和魔兽一样:坚决不做手游...
  5. node.js+Vue计算机毕设项目-Steam游戏平台系统论文(程序+LW+部署)
  6. PDF格式分析(六十一) Text 文字——字体的使用
  7. c语言德•摩根定律编程,【程序中的数学】利用德摩根定律简化布尔运算
  8. 20190710项目日志2
  9. FastText原理
  10. Grafana使用教程