首先需要在Facebook官方注册你的应用,这个不用说,需要注意的是在创建应用的时候需要填写应用的key hashes ,这个可以用cmd命令获取,也可以用代码动态获取,我是用代码动态获取的,下面贴下方法:
// Add code to print out the key hash
@SuppressLint("NewApi")
private fun getKeyHashValue() {
try {
val info = activity!!.getPackageManager().getPackageInfo(
"com.wj.demo",
PackageManager.GET_SIGNATURES)
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
}
} catch (e: PackageManager.NameNotFoundException) {
Log.d("KeyHash:",e.toString())
} catch (e: NoSuchAlgorithmException) {
Log.d("KeyHash:", e.toString())
}
}
然后把打印出来的字符串填写到Facebook开发者后台的key Hashes里面就可以了
然后开始在项目里面集成sdk和初始化sdk,调用登陆方法进行登陆:
在project级别的目录下的build.gradle文件种配置
repositories {
mavenCentral()
}
在app级别的目录下的build.gradle文件种配置sdk依赖:
compile 'com.facebook.android:facebook-android-sdk:4.6.0'
在清单文件种配置下面:
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id" />
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider5555302316225142"
android:exported="true" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="@string/app_name" />
在application种初始化sdk:
FacebookSdk.sdkInitialize(applicationContext)
写登陆的关键代码,我这里整理到了工具类种FaceBookLoginUtil.kt:
import android.annotation.SuppressLint
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.util.Base64
import com.facebook.*
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import org.json.JSONObject
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
/**
* @Description: facebook 登陆二次封装
* @Author: wjj
* @Time: 2018/6/26 15:24
*/
class FaceBookLoginUtil {
val TAG = "FaceBookLoginUtil"
var activity: Activity? = null
var loginManager: LoginManager? = null
var call: CallbackManager? = null
var loginListener:FacebookListener? = null
var mName :String = ""
var mPhoto :String = ""
var mYear :String = "0"
var mMonth :String = "0"
var mDay :String = "0"
/*初始化*/
constructor(activity: Activity, loginListener: FacebookListener) {
this.activity = activity
this.loginListener = loginListener
getKeyHashValue()
//初始化facebook登录服务
call = CallbackManager.Factory.create()
loginManager = LoginManager.getInstance()
loginManager?.registerCallback(call,
object : FacebookCallback {
override fun onSuccess(loginResult: LoginResult) {
Log.e(TAG, "onSuccess")
var accessToken = loginResult.getAccessToken()
userInfo(accessToken)
}
override fun onCancel() {
Log.e(TAG, "onCancel")
loginListener.onCancel()
}
override fun onError(exception: FacebookException) {
Log.e(TAG, "onError")
loginListener.onError()
}
})
}
// Add code to print out the key hash
@SuppressLint("NewApi")
private fun getKeyHashValue() {
try {
val info = activity!!.getPackageManager().getPackageInfo(
"com.wj.demo",
PackageManager.GET_SIGNATURES)
for (signature in info.signatures) {
val md = MessageDigest.getInstance("SHA")
md.update(signature.toByteArray())
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
}
} catch (e: PackageManager.NameNotFoundException) {
Log.d("KeyHash:",e.toString())
} catch (e: NoSuchAlgorithmException) {
Log.d("KeyHash:", e.toString())
}
}
//登陆
fun login() {
loginManager?.logInWithReadPermissions(activity, Arrays.asList("public_profile", "user_friends", "user_status", "user_birthday", "user_location", "user_hometown"))
}
//登出
fun logout() {
loginManager!!.logOut()
}
fun getCallbackManager(): CallbackManager {
return this!!.call!!
}
/*获取个人信息*/
fun userInfo(accessToken: AccessToken) {
var request = GraphRequest.newMeRequest(accessToken, object : GraphRequest.GraphJSONObjectCallback {
override fun onCompleted(obj: JSONObject?, response: GraphResponse?) {
//获取个人信息
val facebook_name = obj?.optString("name")
//生日
val facebook_birthday = (obj?.optString("birthday").toString()).replace("/", "", true).trim()
if (facebook_birthday.length!=0){
mDay = facebook_birthday.substring(0, 2)
mMonth = facebook_birthday.substring(2, 4)
mYear = facebook_birthday.substring(4, 8)
}
//获取用户头像
val object_pic = obj?.optJSONObject("picture")
val object_data = object_pic?.optJSONObject("data")
val facebook_photo = object_data?.optString("url")
mName = facebook_name!!
mPhoto = facebook_photo!!
SharedPreferencesUnitls.setParam(activity,"name",mName)
SharedPreferencesUnitls.setParam(activity,"mPhoto",mPhoto)
SharedPreferencesUnitls.setParam(activity, "comeTimeY", mYear)
SharedPreferencesUnitls.setParam(activity, "comeTimeM", mMonth)
SharedPreferencesUnitls.setParam(activity, "comeTimeD", mDay)
loginListener?.onSuccess()
}
})
var 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()
}
interface FacebookListener{
fun onSuccess()
fun onCancel()
fun onError()
}
}
然后调用关键代码:
class LoginActivity:Activity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
faceBookLoginUtil = FaceBookLoginUtil(this, object : FaceBookLoginUtil.FacebookListener {
override fun onSuccess() {
Toast.makeText(this@LoginActivity, "login success", Toast.LENGTH_SHORT).show()
var intent = Intent(this@LoginActivity,HomeActivity().javaClass)
startActivity(intent)
finish()
}
override fun onCancel() {
Toast.makeText(this@LoginActivity, "Cancel the login", Toast.LENGTH_SHORT).show()
}
override fun onError() {
Toast.makeText(this@LoginActivity, "Loading failure", Toast.LENGTH_SHORT).show()
}
})
//点击登陆的按钮后调用fb登陆
faceBookLoginUtil?.login()
}
}