如何在Android项目的同一活动中整合Google Plus和Facebook身份验证?

时间:2015-07-03 12:04:30

标签: android facebook google-plus

我需要将Facebook和Google Plus整合到相同的活动中,但我没有在其中获得成功。我已经在单个项目中尝试了它们并且它们工作正常但是当我将两个项目一起添加时我的应用程序崩溃了。即使我也尝试过自定义按钮,但它们也不起作用。 目前我的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> {
}

如果有人帮助我的话会很棒。

感谢。

2 个答案:

答案 0 :(得分:5)

我昨天通过在onClick部分

中添加几行来解决我的问题
if (mGoogleApiClient.isConnected()) {
            getProfileInformation();
        } else {
            signInWithGplus();
            getProfileInformation();
        } 
}

答案 1 :(得分:4)

如果您第一次拨打signInWithGplus(),它会尝试访问此时为空的mConnectionResult

之所以这样,是因为你只是在onConnectionFailed()中设置它而不会被调用。