[Android]Facebook 登入
首先下載Facebook的SDK:https://developers.facebook.com/docs/android/
匯入到新專案之後
1.打開res/values/string.xml加入<string name="app_id">AppID</string>
2.打開AndroidManifest.xml 加入<uses-permission android:name="android.permission.INTERNET"/>
3.並新增一個Activity
<activity android:name="com.facebook.LoginActivity" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/app_id"/>
4.在onActivityResult上加入如下
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK)
{
switch (requestCode) {
case 64206:
Session.getActiveSession().onActivityResult(MainActivity.this, requestCode, resultCode, data);
break;
}
}
5.最後就可以加入登入的程式
(一般單純取到Token、UserId、UserName.....等不需權限)
Session.openActiveSession(this, true, new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,Exception exception)
{
if (session.isOpened())
{
System.out.println("session open");
}
}
});
(加入權限的方式)
OpenRequest op = new Session.OpenRequest(actvt);
//如果不想出現登入畫面,讓使用者去略過權限,就不加入setLoginBehavior
op.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
op.setCallback(new StatusCallback() {
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened())
{
System.out.println("token:"+session.getAccessToken());
Request.newMeRequest(session, new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,Response response) {
if (user != null) {
System.out.println("id:"+user.getId());
// user.getBirthday()
// user.getFirstName()
// user.getLastName()
// user.getLink()
// user.getLocation()
// user.getMiddleName()
// user.getName()
// user.getUsername()
System.out.println("email:"+user.asMap().get("email"));
}else {
FacebookRequestError error = response.getError();
if (error != null) {
System.out.println(String.format("Error: %s", error.getErrorMessage()));
}
}
}
}).executeAsync();
}
}
});
//加入權限
List<String> permissions = new ArrayList<String>();
permissions.add("email");
op.setPermissions(permissions);
Session session = new Session.Builder(MainActivity.this).build();
Session.setActiveSession(session);
session.openForPublish(op);
留言
張貼留言