如何使用firebase获取google plus联系人列表?

时间:2017-03-31 10:59:00

标签: android firebase google-plus

我想尝试使用firebase获取Google plus的联系人列表,但是可以使用Google演示示例获取firebase登录信息,但是如何在firebase的帮助下获取Google联系人的联系人列表?我对Google plus SDK和firebase感到困惑,请为此查询提供任何帮助。

1 个答案:

答案 0 :(得分:0)

我创建了一个处理谷歌+

的Util类
public class GooglePlusUtil implements GoogleApiClient.OnConnectionFailedListener {

public static final int RC_SIGN_IN = 007;
public static final int G_LOGIN_CANCELLED = 12051;

private int userIdCounter = 0;
private Context mContext;
private GoogleApiClient mGoogleApiClient;
private FragmentActivity mFragmentActivity;
private GoogleResponse mResponseListener;

/**
 * Instantiates a new Google util.
 *
 * @param context
 * @param activity        the context
 * @param signInPresenter
 */
public GooglePlusUtil(Context context, FragmentActivity activity, SignInPresenter signInPresenter) {
    mContext = context;
    mFragmentActivity = activity;
    mResponseListener = signInPresenter;
    initGPlus();
}

private void initGPlus() {
    // Configure sign-in to request the user's ID, email address, and basic
    // profile. ID and basic profile are included in DEFAULT_SIGN_IN.
    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestEmail()
            .build();

    // Build a GoogleApiClient with access to the Google Sign-In API and the
    // options specified by gso.
    mGoogleApiClient = new GoogleApiClient.Builder(mContext)
            .enableAutoManage(mFragmentActivity, this)
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();
}

/**
 * Call G+ login activity.
 */
public void login() {
    Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
    mFragmentActivity.startActivityForResult(signInIntent, RC_SIGN_IN);
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Crashlytics.log(connectionResult.toString());
    Log.d("ConnectionResult", "G+ " + connectionResult.toString());
}

/**
 * Parse G+ response.
 *
 * @param accountsByType account number id
 * @param acct           G+ response.
 */
public void findAuth(Account[] accountsByType, GoogleSignInAccount acct) {
    matchAccountNumber(accountsByType, acct);
    new GoogleAsyncTask(accountsByType, acct).execute();
}

/**
 * userIdCounter Account Number
 *
 * @param accounts account number id
 * @param acct     G+ response.
 */
private void matchAccountNumber(Account[] accounts, GoogleSignInAccount acct) {
    for (int index = 0; index < accounts.length; index++) {
        if (accounts[index].name.equals(acct.getEmail())) {
            userIdCounter = index;
            break;
        }
    }
}

/**
 * Google login response.
 *
 * @param result G+ instance.
 */
public void handleSignInResult(GoogleSignInResult result) {
    if (result.isSuccess()) {
        GoogleSignInAccount acct = result.getSignInAccount();
        if (acct == null || ActivityCompat.checkSelfPermission(mContext, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        findAuth(AccountManager.get(mContext).getAccountsByType("com.google"), acct);

    } else if (result.getStatus().getStatusCode() == G_LOGIN_CANCELLED) {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.google_login_cancelled));
    } else {
        ToastUtils.getInstance(mContext).showToast(mContext.getString(R.string.message_not_able_to_login_via_google));
    }
}

public class GoogleAsyncTask extends AsyncTask<Void, Void, String> {
    private Account[] mAccountsByType;
    private GoogleSignInAccount mGoogleSignInAccount;

    /**
     * Instantiates a new Google async task.
     *
     * @param accountsByType
     * @param acct
     */
    public GoogleAsyncTask(Account[] accountsByType, GoogleSignInAccount acct) {
        mAccountsByType = accountsByType;
        mGoogleSignInAccount = acct;
    }

    @Override
    protected String doInBackground(Void... params) {
        try {
            return GoogleAuthUtil.getToken(mContext, mAccountsByType[userIdCounter], Constants.OAUTH_URL);
        } catch (UserRecoverableAuthException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
            mResponseListener.onTokenNotFound(e.getIntent(), RC_SIGN_IN);
        } catch (GoogleAuthException | IOException e) {
            Crashlytics.logException(e.getCause());
            AppLogger.e(e);
        }
        return "";
    }

    @Override
    protected void onPostExecute(String token) {
        IsAuthValidRequest isAuthValidRequest = new IsAuthValidRequest();
        isAuthValidRequest.setEmail(mGoogleSignInAccount.getEmail());
        isAuthValidRequest.setFirstName(mGoogleSignInAccount.getDisplayName());
        isAuthValidRequest.setLastName(mGoogleSignInAccount.getFamilyName());
        mResponseListener.onGoogleUserInfoAvailable(isAuthValidRequest, token);
    }
}

public interface GoogleResponse {

    /**
     * When user info and token found.
     *
     * @param isAuthValidRequest info instance.
     * @param token G+.
     */
    void onGoogleUserInfoAvailable(IsAuthValidRequest isAuthValidRequest, String token);

    /**
     * Invoke when auth token not found.
     *
     * @param intent      instance.
     * @param requestCode request code.
     */
    void onTokenNotFound(Intent intent, int requestCode);
}
}