Android 应用程序集成FaceBook 登录及二次封装
1、首先在Facebook 开发者平台注册一个账号
https://developers.facebook.com/
开发者后台 https://developers.facebook.com/apps
2、创建账号并且获得 APP ID
图一
图二
图三
图四
图五
3、获取app签名的Key Hashes 值(两种方式)
获取方式:https://blog.csdn.net/zhaoyanjun6/article/details/105344657
4、设置应用的基本配置
图一
图二
图三
5、App开始集成 FacebookSDk
5.1 在项目的 build.gradle 添加
compile 'com.facebook.android:facebook-android-sdk:4.10.1'
查看最新的版本 : http://search.maven.org/#search%7Cga%7C1%7Ccom.facebook.android
5.2 在应用的 Application 里面初始化SDK
//facebook登录初始化
FacebookSdk.sdkInitialize( getApplicationContext() );
5.3 在value文件夹下 strings.xml 中
<!-- facebook 登录 key-->
<string name="facebook_app_id">1001702146573854</string>
5.4 在 AndroidManifest.xml 中
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity
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>
5.5 在布局文件中定义登录按钮
<com.facebook.login.widget.LoginButton android:id="@+id/facebook_bt" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="facebook login" > </com.facebook.login.widget.LoginButton>
5.6 在代码中实现
1 package com.pegasus.map.presentation.ui.activity; 2 import android.content.Intent; 3 import android.os.Bundle; 4 import android.widget.Toast; 5 import com.facebook.CallbackManager; 6 import com.facebook.FacebookCallback; 7 import com.facebook.FacebookException; 8 import com.facebook.login.LoginResult; 9 import com.facebook.login.widget.LoginButton; 10 import com.pegasus.map.R; 11 import com.pegasus.map.presentation.ui.base.BaseActivity; 12 import butterknife.Bind; 13 import butterknife.ButterKnife; 14 15 16 /** 17 * Created by ${zyj} on 2016/3/24. 18 * 登录 19 */ 20 21 public class LoginLoginActivity extends BaseActivity { 22 23 @Bind(R.id.facebook_bt) 24 public LoginButton facebook_bt; 25 26 private CallbackManager callbackManager ; 27 28 @Override 29 protected void onCreate(Bundle savedInstanceState) { 30 super.onCreate(savedInstanceState); 31 setContentView(R.layout.activity_login); 32 33 ButterKnife.bind(this); 34 callbackManager = CallbackManager.Factory.create() ; 35 36 init(); 37 } 38 39 private void init() { 40 41 facebook_bt.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 42 @Override 43 public void onSuccess(LoginResult loginResult) { 44 Toast.makeText(LoginLoginActivity.this, "facebook登录成功了", Toast.LENGTH_SHORT).show(); 45 log("facebook登录成功了" + loginResult.getAccessToken());
//获取登录信息
getLoginInfo( loginResult.getAccessToken() ) ; 46 } 47 48 @Override 49 public void onCancel() { 50 Toast.makeText(LoginLoginActivity.this, "facebook登录取消了", Toast.LENGTH_SHORT).show(); 51 log("facebook登录取消了"); 52 } 53 54 @Override 55 public void onError(FacebookException error) { 56 Toast.makeText(LoginLoginActivity.this, "facebook登录失败了", Toast.LENGTH_SHORT).show(); 57 log("facebook登录失败了"); 58 } 59 }); 60 61 } 62 63 @Override 64 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 65 super.onActivityResult(requestCode, resultCode, data); 66 67 //facebook回调 68 callbackManager.onActivityResult( requestCode , resultCode ,data ) ; 69 } 70 }
1 /** 2 * 获取登录信息 3 * @param accessToken 4 */ 5 public void getLoginInfo( AccessToken accessToken ){ 6 GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { 7 @Override 8 public void onCompleted(JSONObject object, GraphResponse response) { 9 if (object != null) { 10 String id = object.optString( "id" ) ; //比如:1565455221565 11 String name = object.optString( "name" ) ; //比如:Zhang San 12 String gender = object.optString("gender") ; //性别:比如 male (男) female (女) 13 String emali = object.optString("email") ; //邮箱:比如:56236545@qq.com 14 15 //获取用户头像 16 JSONObject object_pic = object.optJSONObject( "picture" ) ; 17 JSONObject object_data = object_pic.optJSONObject( "data" ) ; 18 String photo = object_data.optString( "url" ) ; 19 20 //获取地域信息 21 String locale = object.optString( "locale" ) ; //zh_CN 代表中文简体 22 23 Toast.makeText( activity , "" + object.toString() , Toast.LENGTH_SHORT).show(); 24 } 25 } 26 }) ; 27 28 Bundle parameters = new Bundle(); 29 parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name"); 30 request.setParameters(parameters); 31 request.executeAsync() ; 32 }
5.7 企业账号需要注意的事项,把发布按钮打开
6、对facebookSDk 进行二次封装
1 package com.pegasus.map.presentation.utils; 2 3 import android.app.Activity; 4 import android.content.DialogInterface; 5 import android.os.Bundle; 6 import android.support.v7.app.AlertDialog; 7 import android.widget.Toast; 8 9 import com.facebook.AccessToken; 10 import com.facebook.CallbackManager; 11 import com.facebook.FacebookCallback; 12 import com.facebook.FacebookException; 13 import com.facebook.GraphRequest; 14 import com.facebook.GraphResponse; 15 import com.facebook.Profile; 16 import com.facebook.login.LoginManager; 17 import com.facebook.login.LoginResult; 18 19 import org.json.JSONObject; 20 21 import java.util.Arrays; 22 import java.util.Collections; 23 import java.util.List; 24 25 /** 26 * Created by ${zyj} on 2016/3/30. 27 */ 28 public class FaceBookLogin { 29 30 private Activity activity ; 31 private CallbackManager callbackManager ; 32 private FacebookListener facebookListener ; 33 private List<String> permissions = Collections.<String>emptyList(); 34 private LoginManager loginManager; 35 36 public FaceBookLogin( Activity activity ){ 37 this.activity = activity ; 38 39 //初始化facebook登录服务 40 callbackManager = CallbackManager.Factory.create() ; 41 getLoginManager().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { 42 @Override 43 public void onSuccess(LoginResult loginResult) { 44 // login success 45 AccessToken accessToken = loginResult.getAccessToken(); 46 getLoginInfo(accessToken); 47 } 48 49 @Override 50 public void onCancel() { 51 //取消登录 52 } 53 54 @Override 55 public void onError(FacebookException error) { 56 //登录出错 57 } 58 }); 59 60 permissions = Arrays 61 .asList("email", "user_likes", "user_status", "user_photos", "user_birthday", "public_profile", "user_friends") ; 62 } 63 64 /** 65 * 登录 66 */ 67 public void login(){ 68 getLoginManager().logInWithReadPermissions( 69 activity, permissions); 70 } 71 72 /** 73 * 退出 74 */ 75 public void logout(){ 76 String logout = activity.getResources().getString( 77 com.facebook.R.string.com_facebook_loginview_log_out_action); 78 String cancel = activity.getResources().getString( 79 com.facebook.R.string.com_facebook_loginview_cancel_action); 80 String message; 81 Profile profile = Profile.getCurrentProfile(); 82 if (profile != null && profile.getName() != null) { 83 message = String.format( 84 activity.getResources().getString( 85 com.facebook.R.string.com_facebook_loginview_logged_in_as), 86 profile.getName()); 87 } else { 88 message = activity.getResources().getString( 89 com.facebook.R.string.com_facebook_loginview_logged_in_using_facebook); 90 } 91 AlertDialog.Builder builder = new AlertDialog.Builder(activity); 92 builder.setMessage(message) 93 .setCancelable(true) 94 .setPositiveButton(logout, new DialogInterface.OnClickListener() { 95 public void onClick(DialogInterface dialog, int which) { 96 getLoginManager().logOut(); 97 } 98 }) 99 .setNegativeButton(cancel, null); 100 builder.create().show(); 101 } 102 103 /** 104 * 获取登录信息 105 * @param accessToken 106 */ 107 public void getLoginInfo( AccessToken accessToken ){ 108 GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() { 109 @Override 110 public void onCompleted(JSONObject object, GraphResponse response) { 111 if (object != null) { 112 String id = object.optString("id"); //比如:1565455221565 113 String name = object.optString("name"); //比如:Zhang San 114 String gender = object.optString("gender"); //性别:比如 male (男) female (女) 115 String emali = object.optString("email"); //邮箱:比如:56236545@qq.com 116 117 //获取用户头像 118 JSONObject object_pic = object.optJSONObject("picture"); 119 JSONObject object_data = object_pic.optJSONObject("data"); 120 String photo = object_data.optString("url"); 121 122 //获取地域信息 123 String locale = object.optString("locale"); //zh_CN 代表中文简体 124 125 Toast.makeText(activity, "" + object.toString(), Toast.LENGTH_SHORT).show(); 126 } 127 } 128 }) ; 129 130 Bundle parameters = new Bundle(); 131 parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name"); 132 request.setParameters(parameters); 133 request.executeAsync() ; 134 } 135 136 /** 137 * 获取loginMananger 138 * @return 139 */ 140 private LoginManager getLoginManager() { 141 if (loginManager == null) { 142 loginManager = LoginManager.getInstance(); 143 } 144 return loginManager; 145 } 146 147 public CallbackManager getCallbackManager(){ 148 return callbackManager ; 149 } 150 151 /** 152 * 设置登录简体器 153 * @param facebookListener 154 */ 155 public void setFacebookListener( FacebookListener facebookListener ){ 156 this.facebookListener =facebookListener ; 157 } 158 159 public interface FacebookListener { 160 void facebookLoginSuccess(); 161 void facebookLoginFail() ; 162 } 163 164 165 }
在 activity 使用
1 //初始化Facebook登录服务 2 FaceBookLogin faceBookLogin = new FaceBookLogin( this ) ; 3 4 //登录 5 faceBookLogin.login(); 6 7 //退出 8 faceBookLogin.logout();
1 @Override 2 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 3 super.onActivityResult(requestCode, resultCode, data); 4 5 //facebook回调 6 faceBookLogin.getCallbackManager().onActivityResult(requestCode, resultCode, data); 7 8 }
最新更新(2020/4/16)
最近有机会又接触到海外项目,刚好要做 facebook 登陆功能,下面我把封装的代码用 Kotlin 实现一遍:
FacebookLoginUtil 工具类
package com.enjoy.literaturemodule.account.login.facebook import android.app.Activity import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AlertDialog import com.facebook.* import com.facebook.AccessToken import com.facebook.login.LoginManager import com.facebook.login.LoginResult import org.json.JSONObject /** * @author yanjun.zhao * @time 2020/3/10 2:35 PM * @desc */ class FacebookLoginUtil(private var activity: Activity) { private var loginManager: LoginManager? = null private val permissions: List<String> private var callbackManager: CallbackManager? = null init { //初始化facebook登录服务 callbackManager = CallbackManager.Factory.create() getLoginManager()?.registerCallback(callbackManager, object : FacebookCallback<LoginResult> { override fun onSuccess(result: LoginResult?) { getLoginInfo(result?.accessToken) } override fun onCancel() { } override fun onError(error: FacebookException?) { } }) permissions = listOf("email", "user_likes", "user_status", "user_photos", "user_birthday", "public_profile", "user_friends"); } /** * 登陆 */ fun login() { getLoginManager().logInWithReadPermissions(activity, permissions) } /** * 退出登陆 */ fun loginOut() { var logout = activity.resources.getString(com.facebook.R.string.com_facebook_loginview_log_out_action) var cancel = activity.resources.getString(com.facebook.R.string.com_facebook_loginview_cancel_action) val message: String val profile: Profile = Profile.getCurrentProfile() message = if (profile?.name != null) { java.lang.String.format( activity.resources.getString( R.string.com_facebook_loginview_logged_in_as), profile.name) } else { activity.resources.getString( R.string.com_facebook_loginview_logged_in_using_facebook) } val builder: AlertDialog.Builder = AlertDialog.Builder(activity) builder.setMessage(message) .setCancelable(true) .setPositiveButton(logout, DialogInterface.OnClickListener { dialog, which -> getLoginManager().logOut() }) .setNegativeButton(cancel, null) builder.create().show() } /** * 获取登录信息 * @param accessToken */ private fun getLoginInfo(accessToken: AccessToken?) { var request = GraphRequest.newMeRequest(accessToken, object : GraphRequest.GraphJSONObjectCallback { override fun onCompleted(`object`: JSONObject?, response: GraphResponse?) { `object`?.run { val id = optString("id") //比如:1565455221565 val name = optString("name") //比如:Zhang San val gender = optString("gender") //性别:比如 male (男) female (女) val emali = optString("email") //邮箱:比如:56236545@qq.com //获取用户头像 val object_pic = optJSONObject("picture") val object_data = object_pic.optJSONObject("data") val photo = object_data.optString("url") //获取地域信息 val locale = optString("locale") //zh_CN 代表中文简体 } } }) val parameters = Bundle() parameters.putString("fields", "id,name,link,gender,birthday,email,picture,locale,updated_time,timezone,age_range,first_name,last_name") request.parameters = parameters request.executeAsync() } fun getCallbackManager(): CallbackManager? { return callbackManager } /** * 获取loginMananger * @return */ private fun getLoginManager(): LoginManager { if (loginManager == null) { loginManager = LoginManager.getInstance(); } return loginManager!! } companion object { /** * 是否处在登陆状态 */ fun isLogin(): Boolean { val accessToken = AccessToken.getCurrentAccessToken() val isLoggedIn = accessToken != null && !accessToken.isExpired return isLogin() } } }
Activity 使用示范
package com.enjoy.literaturemodule.account import android.app.Activity import android.content.Intent import android.os.Bundle import com.enjoy.literaturemodule.R import com.enjoy.literaturemodule.account.login.facebook.FacebookLoginUtil import kotlinx.android.synthetic.main.activity_login.* /** * 登陆 */ class LoginActivity : Activity() { private var faceBookUtil: FacebookLoginUtil? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) faceBookUtil = FacebookLoginUtil(this) facebook_login?.setOnClickListener { faceBookUtil?.login() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { //facebook 登陆 //facebook回调 faceBookUtil?.getCallbackManager()?.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data) } }