2014.01.18 02:07

1. 일단 환경 설정 및 반정도 로그인 연동 기능 구현


public void printHashKey() {

        try {
            PackageInfo info = getPackageManager().getPackageInfo("your.package.name",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("TEMPTAGHASH KEY:",
                        Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {

        }

    }


일단 중요한것


1. 앱 패키지 네임, 클래스 네임

2. 위 매서드를 호출해서 해시값을 가져온다.

3. 앱/페이지를 개설한다.

4. 앱 아이디, 씨크릿, 등등값과 페이지 아이디를 기억한다.

5. 페이스북 sdk를 내려받는다.

6. sdk연결하고 페이스붓 개발자 페이지에서 보여주는 대로 모두 복붙한다. 이 예제는 잘 동작하는것..

7. 앱에 해시값 넣는 부분에 저 위의 매서드 호출로 나온 해시값을 저장한다.



참고로 AndroidAnnotations가 좋긴한듯

일단 Rest api구현이 엄청 쉬움/ 그외 uithread, background thread 처리가 걍 어노테이션 하나로 다 해결!

뷰 연동, 레이아웃 연동 졸라 쉬움.



사용할때는 그래들 연동도 중요하지만 컴파일 옵션에서 어노테이션 프로세싱 툴을 셋팅하는것이 있어야 함.

무슨 기능때문에 스냅샨 버전 3.1 쓰고 있긴 한데 


buildscript {

repositories {

mavenCentral()

}


dependencies {

classpath 'com.android.tools.build:gradle:0.7.+'

}

}


apply plugin: 'android'


ext.daggerVersion = '1.0.0';

androidAnnotationsVersion = '3.1-SNAPSHOT';


repositories {

mavenCentral()

maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }

}


android {

compileSdkVersion 19

buildToolsVersion '17.0.0'

defaultConfig {

minSdkVersion 10

targetSdkVersion 19

versionCode 1

versionName "1.0"

}

buildTypes {

release {

runProguard false

proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'

}

}

packagingOptions {

exclude 'META-INF/dependencies'

exclude 'META-INF/notice'

exclude 'META-INF/license'

exclude 'META-INF/license.txt'

exclude 'META-INF/notice.txt'

}


lintOptions {

quiet true

abortOnError false

}

signingConfigs {

debug {

keyAlias 'photify.keystore'

keyPassword 'photify'

storeFile file('../keystore/photify.keystore')

storePassword 'photify'

}

}

}


configurations {

apt

}


dependencies {

compile 'com.android.support:support-v4:19.0.0'

compile 'com.android.support:gridlayout-v7:19.0.0'

compile 'com.android.support:appcompat-v7:19.0.0'

apt "com.squareup.dagger:dagger-compiler:${daggerVersion}"

compile "com.squareup.dagger:dagger:${daggerVersion}"

apt "org.androidannotations:androidannotations:${androidAnnotationsVersion}"

compile "org.androidannotations:androidannotations-api:${androidAnnotationsVersion}"

compile 'com.google.android.gms:play-services:4.0.30'

compile 'com.google.code.gson:gson:1.7.2'

compile 'com.github.chrisbanes.actionbarpulltorefresh:library:0.9.3'

compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

// compile 'org.springframework.android:spring-android-auth:1.0.1.RELEASE'

compile 'org.springframework.android:spring-android-core:1.0.1.RELEASE'

compile 'com.restfb:restfb:1.6.12'

compile project(':fb')

compile project(':arcmenu')

// compile "de.greenrobot:eventbus:2.2.0" otto 쓸까??

}


android.applicationVariants.all { variant ->

aptOutput = file("${project.buildDir}/source/apt_generated/${variant.dirName}")

println "****************************"

println "variant: ${variant.name}"

println "manifest:  ${variant.processResources.manifestFile}"

println "aptOutput:  ${aptOutput}"

println "****************************"


variant.javaCompile.source = variant.javaCompile.source.filter { p ->

return !p.getPath().startsWith(aptOutput.getPath())

}


variant.javaCompile.doFirst {

println "*** compile doFirst ${variant.name}"

aptOutput.mkdirs()


variant.javaCompile.options.compilerArgs += [

'-classpath', configurations.compile.asPath,

'-processorpath', configurations.apt.getAsPath(),

'-AandroidManifestFile=' + variant.processResources.manifestFile,

'-AresourcePackageName=ac.jejunu.photify',

'-s', aptOutput

]

}

}







package ac.jejunu.photify.activity.fragment;


import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Arrays;

import java.util.Collection;

import java.util.List;


import org.androidannotations.annotations.AfterViews;

import org.androidannotations.annotations.EFragment;

import org.androidannotations.annotations.ViewById;

import org.json.JSONException;

import org.json.JSONObject;


import android.content.Intent;

import android.content.pm.PackageInfo;

import android.content.pm.PackageManager;

import android.content.pm.Signature;

import android.os.Bundle;

import android.support.v4.app.Fragment;

import android.util.Base64;

import android.util.Log;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;

import android.widget.Toast;


import com.facebook.FacebookException;

import com.facebook.FacebookOperationCanceledException;

import com.facebook.FacebookRequestError;

import com.facebook.HttpMethod;

import com.facebook.Request;

import com.facebook.RequestAsyncTask;

import com.facebook.Response;

import com.facebook.Session;

import com.facebook.SessionState;

import com.facebook.UiLifecycleHelper;

import com.facebook.widget.LoginButton;

import com.facebook.widget.WebDialog;


import ac.jejunu.photify.R;

import ac.jejunu.photify.activity.MainActivity;


@EFragment(R.layout.fragment_facebook_login)

public class FacebookLoginFragment extends Fragment {


private static final String TAG = "MainFragment";


@ViewById(R.id.shareButton)

Button shareButton;


@ViewById(R.id.sendRequestButton)

Button sendRequestButton;


@ViewById(R.id.authButton)

LoginButton authButton;


private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");


private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";


private boolean pendingPublishReauthorization = false;


private UiLifecycleHelper uiHelper;


private Session.StatusCallback callback = new Session.StatusCallback() {

@Override

public void call(final Session session, final SessionState state, final Exception exception) {

onSessionStateChange(session, state, exception);

}

};


@AfterViews

void afterViews() {

sendRequestButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

sendRequestDialog();

}

});


authButton.setFragment(this);

shareButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

publishStory();

}

});


printHashKey();

}


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

uiHelper = new UiLifecycleHelper(getActivity(), callback);

uiHelper.onCreate(savedInstanceState);

if (savedInstanceState != null) {

pendingPublishReauthorization =

savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);

}

}


@Override

public void onResume() {

super.onResume();


// For scenarios where the fragment_facebook_login activity is launched and user

// session is not null, the session state change notification

// may not be triggered. Trigger it if it's open/closed.

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);

outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);

uiHelper.onSaveInstanceState(outState);

}


private void onSessionStateChange(Session session, SessionState state, Exception exception) {

Log.e("onSessionStateChange", "state : isOpen?:" + state.isOpened());

if (state.isOpened()) {

shareButton.setVisibility(View.VISIBLE);

if (pendingPublishReauthorization &&

state.equals(SessionState.OPENED_TOKEN_UPDATED)) {

pendingPublishReauthorization = false;

publishStory();

}

sendRequestButton.setVisibility(View.VISIBLE);

} else if (state.isClosed()) {

shareButton.setVisibility(View.INVISIBLE);

sendRequestButton.setVisibility(View.INVISIBLE);

}

}


private void publishStory() {

Session session = Session.getActiveSession();

if (session != null) {


// Check for publish permissions

List<String> permissions = session.getPermissions();

if (!isSubsetOf(PERMISSIONS, permissions)) {

pendingPublishReauthorization = true;

Session.NewPermissionsRequest newPermissionsRequest = new Session

.NewPermissionsRequest(this, PERMISSIONS);

session.requestNewPublishPermissions(newPermissionsRequest);

return;

}


Bundle postParams = new Bundle();

postParams.putString("name", "Facebook SDK for Android");

postParams.putString("caption", "Build great social apps and get more installs.");

postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");

postParams.putString("link", "https://developers.facebook.com/android");

postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");


Request.Callback callback = new Request.Callback() {

public void onCompleted(Response response) {

JSONObject graphResponse = response

.getGraphObject()

.getInnerJSONObject();

String postId = null;

try {

postId = graphResponse.getString("id");

} catch (JSONException e) {

Log.i(TAG,

"JSON error " + e.getMessage());

}

FacebookRequestError error = response.getError();

if (error != null) {

Toast.makeText(getActivity()

.getApplicationContext(),

error.getErrorMessage(),

Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getActivity()

.getApplicationContext(),

postId,

Toast.LENGTH_LONG).show();

// when login is successful

startActivity(new Intent(getActivity().getApplicationContext(), MainActivity.class));

}

}

};


Request request = new Request(session, "me/feed", postParams,

HttpMethod.POST, callback);


RequestAsyncTask task = new RequestAsyncTask(request);

task.execute();

}

}


private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {

for (String string : subset) {

if (!superset.contains(string)) {

return false;

}

}

return true;

}


private void sendRequestDialog() {

Bundle params = new Bundle();

params.putString("message", "Learn how to make your Android apps social");


WebDialog requestsDialog = (

new WebDialog.RequestsDialogBuilder(getActivity(),

Session.getActiveSession(),

params))

.setOnCompleteListener(new WebDialog.OnCompleteListener() {


@Override

public void onComplete(Bundle values,

                      FacebookException error) {

if (error != null) {

if (error instanceof FacebookOperationCanceledException) {

Toast.makeText(getActivity().getApplicationContext(),

"Request cancelled",

Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getActivity().getApplicationContext(),

"Network Error",

Toast.LENGTH_SHORT).show();

}

} else {

final String requestId = values.getString("request");

if (requestId != null) {

Toast.makeText(getActivity().getApplicationContext(),

"Request sent",

Toast.LENGTH_SHORT).show();

} else {

Toast.makeText(getActivity().getApplicationContext(),

"Request cancelled",

Toast.LENGTH_SHORT).show();

}

}

}


})

.build();

requestsDialog.show();

}


public void printHashKey() {

try {

PackageInfo info = getActivity().getPackageManager().getPackageInfo("ac.jejunu.photify", PackageManager.GET_SIGNATURES);

for (Signature signature : info.signatures) {

MessageDigest md = MessageDigest.getInstance("SHA");

md.update(signature.toByteArray());

Log.e("TEMPTAGHASH KEY:", Base64.encodeToString(md.digest(), Base64.DEFAULT));

}

} catch (PackageManager.NameNotFoundException e) {

e.printStackTrace();

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

}

}

}



저작자 표시 비영리 변경 금지
신고
Trackback 0 Comment 0


티스토리 툴바