안드로이드 (3.0) 용 Facebook 최신 SDK를 둘러보기 위해 일주일 간 짧은 시간 동안 내 머리를 벽에 부딪 히고있었습니다. Facebook은 무언가를 과도하게 복잡하게 만들었습니다. 그것은 첫번째 장소에서 부서지지 않았다.활동을 간단한 하나의 버튼으로 변환합니다. Facebook 3.0 로그인
내가 원하는 것은 onClick에서 코드를 작성하는 것입니다.이 코드를 작성하기 위해 작성된 활동 ive의 코드는 아래에 있으며 예, 현재 실행 중입니다. (사용자를 기록하고, 내 API에 요청을 보내며, 그게 무엇인지 생각해보십시오.)
필자는 절대적으로 페이스 북의 "세션"을 관리 할 필요가 없으며 단순히 관리하고 싶습니다. 사용자의 fb 자격 증명을 사용하여 로그인하고, 세션을 열고, 사용자 정보를 얻기위한 단일 요청을 작성하고, 내 API 및 내 자신의 API/공유 환경 설정/세션을 사용하여 인수합니다. 만약 내가 이것을 어떻게 할 수 있는지를 보여줄 스 니펫 (snippet)의 방향으로 나를 가리키기 쉽다면. 아래에서 설정 한 사용 권한 설정과 내 질문에 대한 답변 이상의 활동 편집이 있습니다.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.model.GraphUser;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
public class Old_FB_Login_Activity extends Activity {
private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token=";
private TextView textInstructionsOrLink;
private Button buttonLoginLogout;
private Session.StatusCallback statusCallback = new SessionStatusCallback();
// List of additional write permissions being requested
private static final List<String> PERMISSIONS = Arrays.asList("email","user_about_me","user_activities",
"user_birthday","user_education_history", "user_events","user_hometown", "user_groups","user_interests","user_likes",
"user_location","user_photos","user_work_history");
SharedPrefs sharedprefs;
// Request code for reauthorization requests.
private static final int REAUTH_ACTIVITY_CODE = 100;
// Flag to represent if we are waiting for extended permissions
private boolean pendingAnnounce = false;
protected String college;
private Button buttonLogin;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebooklogin);
buttonLoginLogout = (Button)findViewById(R.id.buttonLoginLogout);
buttonLogin = (Button)findViewById(R.id.login);
textInstructionsOrLink = (TextView)findViewById(R.id.instructionsOrLink);
sharedprefs = new SharedPrefs(getApplicationContext());
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(this, null, statusCallback, savedInstanceState);
}
if (session == null) {
session = new Session(this);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
}
}
updateView();
}
@Override
public void onStart() {
super.onStart();
Session.getActiveSession().addCallback(statusCallback);
}
@Override
public void onStop() {
super.onStop();
Session.getActiveSession().removeCallback(statusCallback);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Session session = Session.getActiveSession();
Session.saveSession(session, outState);
}
private void updateView() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Log.i("permissions",session.getPermissions().toString());
//makeLikesRequest(session);
makeMeRequest(session);
Log.i("token",session.getAccessToken());
Log.i("token experation", session.getExpirationDate().toString());
Intent i = new Intent(getApplicationContext(), FaceTestActivity.class);
startActivity(i);
/*buttonLoginLogout.setText(R.string.logout);
buttonLoginLogout.setOnClickListener(new OnClickListener() {
public void onClick(View view) { onClickLogout(); }
});*/
} else {
textInstructionsOrLink.setText(R.string.instructions);
buttonLoginLogout.setText(R.string.login);
buttonLoginLogout.setOnClickListener(new OnClickListener() {
public void onClick(View view) { onClickLogin(); }
});
}
}
private void onClickLogin() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback).setPermissions(PERMISSIONS));
} else {
Session.openActiveSession(this, true, statusCallback);
}
}
private void onClickLogout() {
Session session = Session.getActiveSession();
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
}
}
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state, Exception exception) {
}
}
/* private void makeLikesRequest(final Session session) {
Request.Callback callback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
// response should have the likes
// If the response is successful
if (session == Session.getActiveSession()) {
Log.i("likes response", response.toString());
}
}
};
Request request = new Request(session, "me/likes", null, HttpMethod.GET, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} */
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
@Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
Log.i("user", user.toString());
JSONObject json = user.getInnerJSONObject();
Log.i("json me response", json.toString());
RequestParams params = new RequestParams();
String fb_token = session.getAccessToken().toString();
String fb_token_expires = session.getExpirationDate().toString();
Log.i("fb_token", fb_token);
params.put("fb_token",fb_token);
Log.i("fb_token_expires", fb_token_expires);
params.put("fb_token_expires",fb_token_expires);
if(user.getBirthday() != null){
String birthday = user.getBirthday();
Log.i("birthday_1",birthday);
params.put("birthday", birthday);
}
if(user.getFirstName() != null){
String firstName = user.getFirstName();
Log.i("first name_2", firstName);
params.put("first_name", firstName);
}
if(user.getLastName() != null){
String lastName = user.getLastName();
Log.i("last name_3", lastName);
params.put("last_name", lastName);
}
if(user.getLink() != null){
String fb_link = user.getLink();
Log.i("fb_link_4", fb_link);
params.put("fb_link", fb_link);
}
if(user.getId() != null){
String fb_uid = user.getId();
Log.i("fb uid_5", fb_uid);
params.put("fb_uid", fb_uid);
}
if(user.getProperty("gender") != null){
String gender = user.getProperty("gender").toString();
Log.i("gender_6", gender);
params.put("gender", gender);
}
if(user.getProperty("email") != null){
String email = user.getProperty("email").toString();
Log.i("email_7", email);
params.put("fb_email", email);
}
if(user.getProperty("verified") != null){
String verified = user.getProperty("verified").toString();
Log.i("verified_8", verified);
params.put("verified", verified);
}
if(user.getProperty("bio") != null){
String bio = user.getProperty("bio").toString();
Log.i("bio_9", bio);
params.put("bio", bio);
}
if(user.getLocation().getProperty("name") != null){
String location = user.getLocation().getProperty("name").toString();
Log.i("location_10", location);
params.put("location", location);
}
//user Location
JSONArray education_array = (JSONArray)user.getProperty("education");
if (education_array.length() > 0) {
String education_length= String.valueOf(education_array.length());
Log.i("education_length",education_length);
ArrayList<String> collegeNames = new ArrayList<String>();
for (int i=0; i < education_array.length(); i++) {
JSONObject edu_obj = education_array.optJSONObject(i);
// Add the language name to a list. Use JSON
// methods to get access to the name field.
String type = edu_obj.optString("type");
Log.i("type of edu", type);
if(type.equalsIgnoreCase("college")){
JSONObject school_obj = edu_obj.optJSONObject("school");
college = school_obj.optString("name");
//Log.i("college",college);
}
}
params.put("college", college);
Log.i("college", college);
}
RestClient.post(FB_LOGIN_URL, params, new JsonHttpResponseHandler() {
@Override
public void onFailure(Throwable arg0, JSONObject arg1) {
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
Log.i("FAILED TO LOGIN:", arg1.toString());
Toast.makeText(getApplicationContext(), arg1.toString() , Toast.LENGTH_LONG).show();
}
@Override
public void onSuccess(JSONObject json) {
Log.i("Login Request Success:", json.toString());
try {
sharedprefs.createFBLoginSession(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(getApplicationContext(), TabHostFragmentActivity.class);
startActivity(i);
finish();
}
});
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
}
안녕하세요 @Matt UILifeCycleHelper를 사용하여 FB 로그인 흐름을 구현하려했는데 FB 응답이 포함 된 'mMap' 필드가있는'data '매개 변수는 null입니다. 왜 이런 일이 일어날까요? – toobsco42