2014/07/11

[Android] FaceBook sdk 登入app





1. 下載Facebook sdk:http://goo.gl/nXEtDY

2. Creat a new app:https://developers.facebook.com/

3. 將你剛剛下載的sdk解壓縮,import existing code 到eclipse

4. 建立你的App project,他會給你一個APP-ID

5. 在project上點右鍵 -> Properties -> Android -> Add(在下方) -> 加入Facebook-sdk

6. 產生HashKey:先打開你的CMD,cd到你的java-jdk目錄,找到/bin
    參考(我的Mac路徑):
    /Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/Home/bin
  enter之後再貼上
?
1
2
keytool -exportcert -alias androiddebugkey -keystore
~/.android/debug.keystore | openssl sha1 -binary | openssl base64
  再按一次enter過後他會叫你輸入密碼,不要理他再按一次enter就好
    你會看到產生一行密碼,這就是hashkey

7. 回到你剛剛在fb申請的那個APP頁面,按Settings -> basic -> Add Platform -> Android
會看到這個,把剛剛產生的hashkey貼到KeyHashes欄位,Single sign on打開


8. 開始寫project囉
在Manifest.xml插入這行
?
1
2
    <uses-permission android:name="android.permission.INTERNET"/>

接著修改Avtivity
我的範例是讓他一進來就要登入,所以我放在MainActivity

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.example.photothrow;
import android.os.Bundle;
import android.app.Activity;
import com.facebook.android.*;
import com.facebook.android.Facebook.*;
public class MainActivity extends Activity {
    private Facebook facebook = new Facebook("你的App-ID");
    /** Called when the activity is first created. */
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        facebook.authorize( this, new DialogListener(){
            @Override
            public void onComplete(Bundle values) {
            // TODO Auto-generated method stub
            }
            @Override
            public void onFacebookError(FacebookError e) {
            // TODO Auto-generated method stub
            }
            @Override
            public void onError(DialogError e) {
            // TODO Auto-generated method stub
            }
            @Override
            public void onCancel() {
            // TODO Auto-generated method stub
            }
        });
    }
}

修改這行
?
1
private Facebook facebook = new Facebook("你的App-ID");

就可以run囉!