gpt4 book ai didi

android - 如何在 Android 项目的同一个 Activity 中将 Google Plus 和 Facebook 身份验证集成在一起?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:42:56 26 4
gpt4 key购买 nike

我需要将 Facebook 和 Google Plus 整合到同一 Activity 中,但我没有成功。我在单个项目中都尝试过,它们工作正常,但是当我将两个项目添加到一起时,我的应用程序崩溃了。即使我也用自定义按钮尝试过它们,但它们也不起作用。目前我的 Facebook 部分工作正常,但在登录时单击 Google 按钮时出现错误。我在这些方法中遇到错误:

private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}

private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}

我在这个类中实现:

public class LoginActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
// Your Facebook APP ID
private static String APP_ID = "XXXXXXXXXXXXXXX"; // Replace with your App
// ID
LinearLayout ll;
// Strings of Facebook
String fb_mUserId = "", fb_mUserToken = "", fb_mUserName = "",
fb_mUserEmail = "", fb_verified_value = "", fb_Task_message;
boolean fb_verified, google_verified;
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
@SuppressWarnings("unused")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
EditText edittext_username, edittext_password;
Button Btn_login, Btn_register;
TextView Text_univesity, errorMsg, tv_forget_password;
LinearLayout ll_google, ll_fb;
static String Username, password, name, Twilio_Id = "",
name_candidate = "", phone_no = "", email_candidate = "",
country = "", mobile_verification = "", fb_id = "";
ImageView im;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
int id, Mode = 0, fb_clicked = 0, google_clicked = 0;
static int user_ids;
String IMEI_number;
GPSTracker gps;
static double latitude = 0.00, longitude = 0.00;
Context context;

private static final int RC_SIGN_IN = 0;
// Logcat tag
private static final String TAG = "LoginActivity";
// Profile pic image size in pixels
// private static final int PROFILE_PIC_SIZE = 400;
// Google client to interact with Google API
private GoogleApiClient mGoogleApiClient;
/**
* A flag indicating that a PendingIntent is in progress and prevents us
* from starting further intents.
*/
private boolean mIntentInProgress;
private boolean mSignInClicked;
private ConnectionResult mConnectionResult;
// Strings of Google Plus
String google_email="", google_id="", google_name="", google_verified_value="";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
IMEI_number = telephonyManager.getDeviceId();
im = (ImageView) findViewById(R.id.header);
mAsyncRunner = new AsyncFacebookRunner(facebook);


if (Mode == 3) {
if (login_details.contains("name")) {
name = login_details.getString("name", "");
Intercom.client().registerIdentifiedUser(
new Registration().withUserId(name));
} else {
Intercom.client().registerIdentifiedUser(
new Registration().withUserId("123456"));
}
// We're logged in, we can register the user with Intercom
// Carry on as normal
Intent mode = new Intent(LoginActivity.this, MenuItems.class);
startActivity(mode);
finish();
} else {
edittext_password = (EditText) findViewById(R.id.et_login_password);
Btn_login = (Button) findViewById(R.id.btn_login);
Btn_register = (Button) findViewById(R.id.btn_login_register);
ll_fb = (LinearLayout) findViewById(R.id.login_fb);
ll_google = (LinearLayout) findViewById(R.id.login_google);
tv_forget_password = (TextView) findViewById(R.id.tv_login_forget_password);
Btn_login.setOnClickListener(this);
Btn_register.setOnClickListener(this);
ll_fb.setOnClickListener(this);
ll_google.setOnClickListener(this);
tv_forget_password.setOnClickListener(this);

// Initializing google plus api client
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).addApi(Plus.API)
.addScope(Plus.SCOPE_PLUS_PROFILE).build();
}

}

@Override
public void onClick(View v) {
switch (v.getId()) {

case R.id.btn_login:
// Direct Login Process
break;
case R.id.btn_login_register:
// Direct register process
finish();
break;
case R.id.login_fb:
fb_clicked++;
loginToFacebook();
getProfileInformation();
if (!fb_mUserEmail.equals("")) {
if (fb_verified == true) {
fb_verified_value = "1";
} else {
fb_verified_value = "0";
}
new FacebookAsynTask().execute();
}
break;
case R.id.login_google:
google_clicked++;
signInWithGplus();
// getGoogleProfileInformation();
if (!google_email.equals("")) {
if (google_verified == true) {
google_verified_value = "1";
} else {
google_verified_value = "0";
}
new GoogleAsynTask().execute();
}
break;
case R.id.tv_login_forget_password:
break;

}
}

@Override
protected void onResume() {
super.onResume();
}

protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}

protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}

/** LOGIN TO FACEBOOK */
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);

if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
Toast.makeText(LoginActivity.this, "FIRST CASE", Toast.LENGTH_SHORT)
.show();
getProfileInformation();
}

if (expires != 0) {
facebook.setAccessExpires(expires);
}

if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_actions" },
new DialogListener() {

@Override
public void onCancel() {
// Function to handle cancel event
}

@Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Toast.makeText(LoginActivity.this, "SECOND CASE",
Toast.LENGTH_SHORT).show();
getProfileInformation();

// Making Login button invisible

}

public void onError(DialogError error) {
// Function to handle error
}

public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}

});
}
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (fb_clicked != 0) {
facebook.authorizeCallback(requestCode, resultCode, data);
fb_clicked = 0;
}
else if (google_clicked != 0) {

if (requestCode == RC_SIGN_IN) {
if (resultCode != RESULT_OK) {
mSignInClicked = false;
}

mIntentInProgress = false;

if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
google_clicked = 0;
}
}

/**
* Get Profile information by making request to Facebook Graph API
* */
public void getProfileInformation() {
try {

JSONObject profile = Util.parseJson(facebook.request("me"));
Log.e("Profile", "" + profile);
fb_mUserId = profile.getString("id");
fb_verified = profile.getBoolean("verified");
fb_mUserToken = facebook.getAccessToken();
fb_mUserName = profile.getString("name");
fb_mUserEmail = profile.getString("email");

runOnUiThread(new Runnable() {

public void run() {

Log.e("FaceBook_Profile", "" + fb_mUserId + "\n"
+ fb_mUserToken + "\n" + fb_mUserName + "\n"
+ fb_mUserEmail);
}
});

} catch (FacebookError e) {

e.printStackTrace();
} catch (MalformedURLException e) {

e.printStackTrace();
} catch (JSONException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}
}

/** AsyncTask of Direct Login */


class FacebookAsynTask extends AsyncTask<Void, Void, Void> {

}

/** GOOGLE's CODE STARTS */
/**
* Sign-in into google
* */
private void signInWithGplus() {
if (!mGoogleApiClient.isConnecting()) {
mSignInClicked = true;
resolveSignInError();
}
}

/**
* Method to resolve any signin errors
* */
private void resolveSignInError() {
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}

@Override
public void onConnectionFailed(ConnectionResult result) {
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this,
0).show();
return;
}

if (!mIntentInProgress) {
// Store the ConnectionResult for later usage
mConnectionResult = result;

if (mSignInClicked) {
// The user has already clicked 'sign-in' so we attempt to
// resolve all
// errors until the user is signed in, or they cancel.
resolveSignInError();
}
}

}

@Override
public void onConnected(Bundle arg0) {
mSignInClicked = false;
Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();

// Get user's information
getGoogleProfileInformation();

// Update the UI after signin
// updateUI(true);

}

@Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
// updateUI(false);
}

/**
* Fetching user's information name, email, profile pic
* */
private void getGoogleProfileInformation() {
try {
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi
.getCurrentPerson(mGoogleApiClient);
google_name = currentPerson.getDisplayName();
google_id = currentPerson.getId();
google_verified = currentPerson.isVerified();
String personPhotoUrl = currentPerson.getImage().getUrl();
String personGooglePlusProfile = currentPerson.getUrl();
google_email = Plus.AccountApi.getAccountName(mGoogleApiClient);

Log.e(TAG, "Name: " + google_name + ", plusProfile: "
+ personGooglePlusProfile + ", email: " + google_email
+ ", Image: " + personPhotoUrl);

// by default the profile url gives 50x50 px image only
// we can replace the value with whatever dimension we want by
// replacing sz=X

} else {
Toast.makeText(getApplicationContext(),
"Person information is null", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}

class GoogleAsynTask extends AsyncTask<Void, Void, Void> {
}

如果有人能帮助我,那就太好了。

谢谢。

最佳答案

我昨天通过在 onClick 部分添加几行来自己解决了我的问题

if (mGoogleApiClient.isConnected()) {
getProfileInformation();
} else {
signInWithGplus();
getProfileInformation();
}
}

关于android - 如何在 Android 项目的同一个 Activity 中将 Google Plus 和 Facebook 身份验证集成在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31206448/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com