FaceBook第三方登录的接入封装

  • Post author:
  • Post category:其他



最近公司有一个app上线,并发布海外一个版本,对于登录的话就需要接入FaceBook ,Twitter,Instagram登录,首先向讲述一下FaceBook的登录接入,到FaceBook官网注册应用,主要有三个东西,app_id,这个是在代码中使用的配置的, shaHash值,这个后面讲,然后按照步骤将需要配置都配置一下就好了




第一步:


导入FaceBook的依赖包,FaceBook的依赖包是.arr库,我这里使用的是最新的facebook-android-sdk-4.18.0.aar,也可以直接放在libs库中使用,在app的build.gradle中配置一下内容即可:


repositories{


flatDir {


dirs ‘libs’

}}


在依赖下面添加


compile(name: ‘facebook-android-sdk-4.18.0’, ext: ‘aar’),




配置清单文件


<meta-data
    android:name="com.facebook.sdk.ApplicationId"
    android:value="@string/facebook_app_id"/>

<activity
    tools:replace="android:theme"
    android:name="com.facebook.FacebookActivity"
    android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
    android:theme="@android:style/Theme.Translucent.NoTitleBar"
    android:label="@string/app_name"
    >
</activity>
<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>


string.xml文件中的配置


<string name="facebook_app_id">237361146701659</string>  //这个是注册应用的appId
<string name="fb_login_protocol_scheme">fb1630114020623262</string>


FaceBook的SDK就集成完毕了




第二步:登录的封装


public class FaceBookPlatform extends Platform {

    private final CallbackManager callbackManager;
    private final List<String> permissions;
    private LoginManager loginManager;
    private Activity context;
    public boolean isFaceBook = false;

    public FaceBookPlatform(final Activity context) {
        super(context);
        this.context = context;
        callbackManager = CallbackManager.Factory.create();
        getLoginManager().registerCallback(callbackManager, callback);
        permissions = Arrays.asList("email", "user_likes",
                "user_status", "user_photos", "user_birthday", "public_profile", "user_friends");
    }

    //注册回调
    FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            isFaceBook = false;
            //Toast.makeText(context, "login successful", Toast.LENGTH_SHORT).show();
            hideWait();
            //获取用户信息
            getLoginInfo(loginResult.getAccessToken());
            AccessToken accessToken = loginResult.getAccessToken();
            String userId = accessToken.getUserId();
            String token = accessToken.getToken();
            LogUtils.e("------" +"userId=" + userId);
            LogUtils.e("------" +"token=" + token);
           if (loginResult.getAccessToken() != null) {
                LogUtils.e("-----  进入主页面" );
               ********************处理登录成功后的逻辑******************************
           }
        }

        @Override
        public void onCancel() {
            isFaceBook = false;
            //取消登录
            hideWait();
            Toast.makeText(context, "login cancel", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onError(FacebookException error) {
            //登录出错
            isFaceBook = false;
            hideWait();
            Toast.makeText(context, "something wrong", Toast.LENGTH_SHORT).show();
            LogUtils.e("------" +"error.toString()=" + error.toString());
        }
    };

    public void login(Activity activity) {
        getLoginManager().logInWithReadPermissions(
                activity, permissions);
        isFaceBook = true;
    }

    /**
     * 退出
     */
    public void logout() {
        String logout = context.getResources().getString(
                com.facebook.R.string.com_facebook_loginview_log_out_action);
        String cancel = context.getResources().getString(
                com.facebook.R.string.com_facebook_loginview_cancel_action);
        String message;
        Profile profile = Profile.getCurrentProfile();
        if (profile != null && profile.getName() != null) {
            message = String.format(
                    context.getResources().getString(
                            com.facebook.R.string.com_facebook_loginview_logged_in_as),
                    profile.getName());
        } else {
            message = context.getResources().getString(
                    com.facebook.R.string.com_facebook_loginview_logged_in_using_facebook);
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage(message)
                .setCancelable(true)
                .setPositiveButton(logout, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        getLoginManager().logOut();
                    }
                })
                .setNegativeButton(cancel, null);
        builder.create().show();
    }


    private LoginManager getLoginManager() {
        if (loginManager == null) {
            loginManager = LoginManager.getInstance();
        }
        return loginManager;
    }


    public void getLoginInfo(AccessToken accessToken) {
        GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                if (object != null) {
                    String id = object.optString("id");
                    String name = object.optString("name");
                    String gender = object.optString("gender");
                    String emali = object.optString("email");
                    JSONObject object_pic = object.optJSONObject("picture");
                    JSONObject object_data = object_pic.optJSONObject("data");
                    String photo = object_data.optString("url");
                    //获取地域信息
                    String locale = object.optString("locale");
                   // Toast.makeText(context, "" + object.toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale," +
                "updated_time,timezone,age_range,first_name,last_name");
        request.setParameters(parameters);
        request.executeAsync();
    }


    public CallbackManager getCallbackManager() {
        return callbackManager;
    }

    /**
     * 设置接口回调
     *
     */
    private FacebookListener facebookListener;

    public void setFacebookListener(FacebookListener facebookListener) {
        this.facebookListener = facebookListener;
    }

    public interface FacebookListener {
        void facebookLoginSuccess();

        void facebookLoginFail();
    }

    public boolean getIssFaceBook() {
        return isFaceBook;
    }
}






第三部:在activity设置点击事件的地方调用:




//创建登录平台的对象




faceBookPlatform = new FaceBookPlatform(this);



faceBookPlatform.login(this);



//重写onActivityResult方法

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    //faceBook的回调
    if (faceBookPlatform.getIssFaceBook()) {
        faceBookPlatform.getCallbackManager().onActivityResult(requestCode, resultCode, data);
  
    super.onActivityResult(requestCode, resultCode, data);

}




重要提示:需要的在application中初始化FaceBook的SDK

//初始化faceBook的SDK
FacebookSdk.sdkInitialize( getApplicationContext());


注意点


并且当你在用手机测试的时候如果手机装了FaceBook是登录出错的,因为测试的时候是用的debug的apk,而在注册应用的时候核算shahash值的时候使用的release的apk,他们的hash值不一样,测试只能打开网页登录




另外还有一个类


public class Platform  {

    public Context context;

    private ProgressLoad load;

    public Platform(Context context){
        this.context = context;
        init();
    }

    private void init(){
        if(load == null){
            load = new ProgressLoad(context);
        }
    }

    public void showWait(){
        load.show();
    }

    public void hideWait(){
        load.dismiss();
    }
}




公司集成使用正常


:如有问题请指出













版权声明:本文为puyaCheer原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。