如何在不使用google plus的情况下登录我的Android应用程序。 我需要在我的应用程序中登录谷歌就像我们登录Facebook一样,出现了一个屏幕,要求您填写用户名和密码,然后点击登录按钮。
我直接使用谷歌播放库签名,但我想要提示,并要求输入用户名和密码。
我在使用google plus时遇到的问题是,如果有任何机构有谷歌帐户但没有激活其谷歌加帐户,那么在这种情况下我该怎么办?
我希望谷歌签到这种方式有任何方法请尽快给我解决方案。
答案 0 :(得分:0)
您好,您可以使用以下方法:首先,要求用户在editText中输入电子邮件ID并点击某个按钮获取该值,然后按以下步骤操作:
//Check whether account is already configured or not
if(isAccountAlreadyConfigured(emailId)){
//If the email id entered by user is already configured in the device
getGoogleApiClientInstance(emailId);
connectToGoogleApiClient();
}else{
//If that email id account is not configured in the device
Bundle accountOptions = new Bundle();
accountOptions.putString(AccountManager.KEY_ACCOUNT_NAME, emailId);
accountOptions.putString(AccountManager.KEY_ACCOUNT_TYPE,Constants.ACCOUNT_TYPE);
accountManager.addAccount(Constants.ACCOUNT_TYPE, null, null, accountOptions, this, accountManagerCallback, null);
}
/* @method isAccountAlreadyConfigured is used to check whether the email address entered by user is already
* configured in the device or not
* @param String: it takes the email address as the parameter
* @return boolean*/
private boolean isAccountAlreadyConfigured(String accountName){
Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
for(Account account: accounts ){
if(account.name.equals(accountName)){
//Account alreadyConfiguredAccount = account; //Use this for confirmCredentialsMethod
return true;
}
Log.i(LOG_TAG, "Account info: "+account.name + "\n" + "Account type: "+account.type);
}
return false;
}
/* @method getGoogleApiClientInstance is used to get GoogleApiClientInstance for a particular google account
* @Param String : gmail account Id
* @return GoogleApiClient instance
* */
private GoogleApiClient getGoogleApiClientInstance(String accountName){
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_LOGIN)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.setAccountName(accountName)
.build();
return mGoogleApiClient;
}
/* @method connectToGoogleApiClient is used to connect GoogleApiClient instance to Google API servers */
private void connectToGoogleApiClient(){
if(mGoogleApiClient != null){
mGoogleApiClient.connect();
}else{
Log.e(LOG_TAG, "Error connecting google api client");
}
}
/* accountManagerCallback is used to pass as one of the params to AccountManager.addAccount method*/
private AccountManagerCallback<Bundle> accountManagerCallback = new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
futureBundle = future;
Log.i(LOG_TAG, "Done: " +future.isDone() + "\n" + "isCancelled: "+future.isCancelled());
handler.post(runnable);
}
};
private Runnable runnable = new Runnable() {
@Override
public void run() {
try {
// futureBundle.getResult() call will block until the result is available so we call it on another thread
Bundle bundle = futureBundle.getResult();
if(bundle != null){
Log.i(LOG_TAG, "Result: "+bundle);
String authAccount = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
/*Result bundle should have authAccount and accountType as the extras, this acts as a confirmation that
the account is properly configured in the device or we can cross verify by calling
@method isAccountAlreadyConfigured*/
if((authAccount.equals(emailId) && accountType.equals(Constants.ACCOUNT_TYPE)) || isAccountAlreadyConfigured(emailId)){
getGoogleApiClientInstance(emailId);
connectToGoogleApiClient();
}else{
Log.e(LOG_TAG, "An error occured while configuring new account");
}
}
} catch (OperationCanceledException e) {
e.printStackTrace();
} catch (AuthenticatorException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
如果您不想为已配置的帐户使用GoogleApiClient实例,则可以使用以下代码。以上如果
if(isAccountAlreadyConfigured(emailId)){
Bundle accountOptions = new Bundle();
accountOptions.putString(AccountManager.KEY_ACCOUNT_NAME, emailId);
accountOptions.putString(AccountManager.KEY_ACCOUNT_TYPE,"com.google");
accountManager.confirmCredentials(account, accountOptions, this, accountManagerCallback, null);
}
第一个参数帐户属于Account类,您可以从isAccountAlreadyConfiguredMethod中检索。
答案 1 :(得分:0)
<强>依赖强> 需要互联网许可
工作代码请参阅Play商店中的链接 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**
工作代码请参阅Play商店中的链接 https://play.google.com/store/search?q=com.codecube.airbucks
如果有帮助,请点赞这篇文章
答案 2 :(得分:0)
on adding
Bundle accountOptions = new Bundle();
accountOptions.putString(AccountManager.KEY_ACCOUNT_NAME, emailId);
accountOptions.putString(AccountManager.KEY_PASSWORD, password);
accountOptions.putString(AccountManager.KEY_ACCOUNT_TYPE,Constants.ACCOUNT_TYPE);
accountManager.addAccount(Constants.ACCOUNT_TYPE, null, null, accountOptions, this, accountManagerCallback, null);