"안드로이드 MyFacebookApp 프로젝트 1"의 두 판 사이의 차이

151번째 줄: 151번째 줄:
</source>
</source>
:→ com.facebook.widget.LoginButton 추가됨
:→ com.facebook.widget.LoginButton 추가됨
==AndroidManifest.xml 수정==
{{참고|AndroidManifest.xml}}
*Package --- MyFacebookApp --- AndroidManifest.xml --- Open With --- Android Common XML Editor
*파일 내용을 다음으로 교체하고 저장
<source lang='xml'>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.myfacebookapp"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16"
        tools:ignore="OldTargetApi" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.myfacebookapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name" />
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id" />
    </application>
</manifest>
</source>
:→ android.permission.INTERNET, com.facebook.LoginActivity, com.facebook.sdk.ApplicationId 가 추가되었다.
:→ Warning을 없애기 위해 uses-sdk태그에 tools:ignore="OldTargetApi" 옵션을 추가하였다.


==MainFragment.java 생성==
==MainFragment.java 생성==

2013년 1월 14일 (월) 01:26 판

안드로이드 MyFacebookApp 프로젝트

1 사전 작업

2 새 프로젝트

  • File --- New --- Android Application Project
  • "New Android Application" --- Application Name: My Facebook App[1] --- [Next >]
  • "Configure Project" --- [Next >]
  • "Configure Launcher Icon" --- [Next >]
  • "Create Activity"[2] --- [Next >]
  • "New Blank Activity" --- [Finish]

FacebookSDK를 라이브러리로 지정

  • Package Explorer --- MyFacebookApp 우클릭 --- Properties
  • "Properties for MyFacebookApp" --- Android --- "Library" --- [Add...]
  • "Project Selection" --- FacebookSDK 선택 --- [OK]
  • [OK]

그러면 Problems 창과 Console 창에 오류메시지가 나타난다.

Problems
Jar mismatch! Fix your dependencies	MyFacebookApp		Unknown	Android
Console
[2013-01-13 11:33:31 - MyFacebookApp] Found 2 versions of android-support-v4.jar in the dependency list,
[2013-01-13 11:33:31 - MyFacebookApp] but not all the versions are identical (check is based on SHA-1 only at this time).
[2013-01-13 11:33:31 - MyFacebookApp] All versions of the libraries must be the same at this time.
[2013-01-13 11:33:31 - MyFacebookApp] Versions found are:
[2013-01-13 11:33:31 - MyFacebookApp] Path: D:\workspace\adt\MyFacebookApp\libs\android-support-v4.jar
[2013-01-13 11:33:31 - MyFacebookApp] 	Length: 385685
[2013-01-13 11:33:31 - MyFacebookApp] 	SHA-1: 43c34bc56de78901f234567890123a4567bc890d
[2013-01-13 11:33:31 - MyFacebookApp] Path: D:\workspace\adt\FacebookSDK\libs\android-support-v4.jar
[2013-01-13 11:33:31 - MyFacebookApp] 	Length: 349252
[2013-01-13 11:33:31 - MyFacebookApp] 	SHA-1: 612345c6789012a345b678901a72bc3de890f123
[2013-01-13 11:33:31 - MyFacebookApp] Jar mismatch! Fix your dependencies
→ FacebookSDK와 MyFacebookApp 둘다 android-support-v4.jar를 가지고 있어서 충돌이 나는 것이다.
→ 어느 한쪽을 제거해주면 된다.
  • Package Explorer --- MyFacebookApp --- libs --- android-support-v4.jar 우클릭 --- Delete
  • "Confirm Delete" --- [OK]

이제 오류가 사라졌다. 실행시켜보자.

  • Package Explorer --- MyFacebookApp 우클릭 --- Run as --- 1 Android Application

오류없이 정상적으로 시작은 되는데, 로그인 버튼을 누르면 오류를 내며 중지된다.

3 KeyHash 값 추출 및 입력

(자신의 컴퓨터의 KeyHash 값을 알고 있다면 이 문단은 넘어가도 된다.)

  • MainActivity.java을 다음 내용으로 교체
package com.example.myfacebookapp;

import java.security.MessageDigest;
import android.os.Bundle;
import android.app.Activity;
import android.content.pm.*;
import android.util.*;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		String packageName = "com.example.myfacebookapp"; 
		try {
			PackageInfo info = getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
			for (Signature signature : info.signatures) {
				MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
		        Log.d("Package:", packageName);
				Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
			}
		} catch (Exception e) {
			Log.e("Error", e.toString());
		}
	}
}
→ onCreate 수정하여 KeyHash가 출력되도록 함
→ onCreateOptionsMenu 를 삭제함
  • Ctrl+S 눌러 저장
  • Ctrl+F11 눌러 실행

앱이 실행되면 LogCat 창에 다음과 같이 KeyHash가 출력된다.

01-13 11:11:04.717: D/Package:(820): com.example.myfacebookapp
01-13 11:11:04.727: D/KeyHash:(820): kM1abc2d345ef6I+XKg8LZEhiwU=
→ KeyHash 값은 kM1abc2d345ef6I+XKg8LZEhiwU= 이다.
→ 다른 기기(실제기기든 가상기기든)에서 실행해도 KeyHash 값은 같다.
→ 다른 프로젝트에서도 KeyHash 값은 같다.

KeyHash 값은 컴파일하는 컴퓨터에서 생성되는 값이기 때문에 기기 또는 프로젝트와는 무관하다. 나중에 이 값을 페이스북에 입력해야 하므로 별도의 장소에 기록해두자.

4 페이스북 앱ID 발급

  • App ID와 App Secret을 발급받는다.

5 strings.xml 수정

strings.xml를 수정하여 app_id에 페이스북 앱ID를 입력한다.

  • Package Explorer --- MyFacebookApp --- res --- values --- strings.xml 우클릭 --- Open with --- Android Common XML Editor
  • 파일 내용을 다음으로 교체하고 저장
(단, "앱아이디" 부분에는 발급받은 페이스북 앱ID를 입력한다.)
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">My Facebook App</string>
    <string name="app_id">앱아이디</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>

</resources>
<string name="app_id">앱아이디</string>이 추가되었다.

6 activity_main.xml 수정

  • Package Explorer --- MyFacebookApp --- res --- layout --- activity_main.xml 우클릭 --- Open with --- Android Common XML Editor
  • 파일 내용을 다음으로 교체하고 저장
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <com.facebook.widget.LoginButton
        android:id="@+id/authButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30dp" />

</RelativeLayout>
→ com.facebook.widget.LoginButton 추가됨

7 MainFragment.java 생성

  • ADT --- MyFacebookApp --- src --- com.example.myfacebookapp 우클릭 --- New --- Class
  • "New Java Class" --- Name: MainFragment --- Superclass: android.support.v4.app.Fragment --- [Finish]
  • 파일 내용을 다음으로 교체
package com.example.myfacebookapp;

import java.util.Arrays;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;

public class MainFragment extends Fragment {
	private UiLifecycleHelper uiHelper;
	private static final String TAG = "MainFragment";
	private View mainView; 
	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.activity_main, container, false);

		LoginButton authButton = (LoginButton) mainView.findViewById(R.id.authButton);
		authButton.setFragment(this);
		authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));

		return mainView;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(getActivity(), callback);
		uiHelper.onCreate(savedInstanceState);
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (state.isOpened()) {
			Log.i(TAG, "Logged In...");
			Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

				// callback after Graph API response with user object
				@Override
				public void onCompleted(GraphUser user, Response response) {
					if (user != null) {
						//Log.i("user.getName()", user.getName());
						TextView textView1 = (TextView) mainView.findViewById(R.id.textView1);
						textView1.setText("Hello " + user.getName() + "!");
					}
				}
			});
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
			TextView textView1 = (TextView) mainView.findViewById(R.id.textView1);
			textView1.setText("Hello anonymous!");
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		Session session = Session.getActiveSession();
		if (session != null && (session.isOpened() || session.isClosed()) ) {
			onSessionStateChange(session, session.getState(), null);
		}
		uiHelper.onResume();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
	}
}

8 MainActivity.java 수정

  • Package Explorer --- MyFacebookApp --- src --- com.example.myfacebookapp --- MainActivity.java 더블클릭
  • 파일 내용을 다음으로 교체하고 저장
package com.example.myfacebookapp;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.TextView;

import com.facebook.*;
import com.facebook.model.*;

public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// start Facebook Login
		Session.openActiveSession(this, true, new Session.StatusCallback() {

			// callback when session changes state
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				if (session.isOpened()) {

					// make request to the /me API
					Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

						// callback after Graph API response with user object
						@Override
						public void onCompleted(GraphUser user, Response response) {
							if (user != null) {
								TextView textView1 = (TextView) findViewById(R.id.textView1);
								textView1.setText("Hello " + user.getName() + "!");
							}
						}
					});
				}
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
	}
}
→ onCreate 수정됨
→ onActivityResult 추가됨

9 앱 정보 등록

  • https://developers.facebook.com/apps 접속
  • "Facebook 로그인" --- 이메일/비밀번호 입력하여 로그인
  • [앱 수정]
  • "앱 > First Android App > Basic"
  • "어떻게 앱을 Facebook과 통합시킬지 선택하세요" --- [네이티브 Android 앱]
  • Package Name: com.example.myfacebookapp --- Class Name: com.example.myfacebookapp.MainActivity --- Key Hashes: (위에서 얻은 KeyHash를 입력)[3] --- Facebook 로그인: (O) 활성화됨 --- [변경 내용 저장]

10 실행

  • Ctrl+F11 눌러 실행
Facebook
My Facebook App would like to access your public profile and friend list.
Cancel | OK

11 같이 보기

12 주석

  1. 앱 이름만 입력하면 프로젝트명과 패키지명은 자동으로 채워진다.
  2. BlankActivity가 기본값
  3. 예시에서는 kM1abc2d345ef6I+XKg8LZEhiwU=

13 참고 자료

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}