很长一段时间以来,我使用的登录名几乎与本教程中的登录名相同,直到我意识到它已被弃用。
因此,像一个优秀的开发人员一样,我决定尝试将我的登录升级到 Facebook Android 3.0 SDK,但当我查看文档时,我不禁想知道为什么 Facebook 会在旧版本运行良好的情况下过度复杂化他们的登录。
我当前的代码如下,但我有点困惑。我过去只是简单地向 Facebook 发出授权请求,从他们那里获取一些信息,将其与我的数据库进行比较,如果它匹配 id,则将一些信息保存到共享首选项并打开我的应用程序的家庭活动。但是,对于 3.0 和“会话”,我有点困惑:
- 我是否必须在所有活动中使用这些“会话”?
- 如果是这样,它们会在我的应用程序中持续存在吗?
- 如果我们已经共享首选项,那么会话的意义何在?
编码:
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 FBLoginActivity 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;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebooklogin);
buttonLoginLogout = (Button)findViewById(R.id.buttonLoginLogout);
textInstructionsOrLink = (TextView)findViewById(R.id.instructionsOrLink);
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) {
updateView();
}
}
/* 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);
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("firstName", firstName);
}
if(user.getLastName() != null){
String lastName = user.getLastName();
Log.i("last name_3", lastName);
params.put("lastName", 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("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.createLoginSession(json);
HashMap<String, String> user = sharedprefs.getUserDetails();
String profile_uid = user.get(sharedprefs.KEY_UID);
Intent i = new Intent(getApplicationContext(), TabHostFragmentActivity.class);
i.putExtra("profile_uid", profile_uid);
startActivity(i);
finish();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
}