正确使用Facebook登录 [英] Using facebook login correctly
问题描述
在我的开始页面上应用程序,我要求用户通过Facebook进行身份验证,然后我要求一些权限和获取的一些信息:
In my application on the start page I ask the user to authenticate via Facebook, then I request for some permissions and fetch some information:
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
fb = new FacebookMain();
我能够获得所有这些信息,但是移动到我的下一个页面我想给我的列表视图,并从那里用户可以张贴在墙上的朋友一个按钮。我跟着HelloFacebook样本,它的工作原理就像一个魅力,但是,在我的情况下,当我试图在一个片段不工作打算,我不希望用户登录每次他想发布的时间来实现它(我使用的是其他权限在这里 - 后)我必须实现这里的所有lifecycly事件,在这个片段?是否有任何其他或推荐的方法呢?
I am able to get all this information, but moving to my next page I want to give a button on my listview and from there a user can post on a friends wall. I followed the HelloFacebook sample and it works like a charm, however in my case when I try to implement it in a fragment it does not work as intended, I dont want the user to login every time he wants to post (I am using an additional permission here -- to post) DO I have to implement all the lifecycly events here, in this fragment? Is there any other or recommended approach to this?
目前我在做什么是:
我的类声明:
public class FragmentTab1 extends Fragment {
类级别的变量:
Class level variables:
String FACEBOOK_ID;
String IMAGE_CONTENT;
EditText SEARCH;
private static final String PERMISSION = "publish_actions";
Session session;
private final String PENDING_ACTION_BUNDLE_KEY = "com.exa.digitalrem:PendingAction";
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;
private UiLifecycleHelper uiHelper;
有关Facebook的功能:
Functions related to facebook:
private PendingAction pendingAction = PendingAction.NONE;
private GraphUser user1;
private enum PendingAction {
NONE, POST_PHOTO, POST_STATUS_UPDATE
}
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
public static boolean isActive() {
Session session = Session.getActiveSession();
if (session == null) {
return false;
}
return session.isOpened();
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
new AlertDialog.Builder(getActivity()) .setTitle("cancelled").setMessage("NotGranted").setPositiveButton("Ok", null).show();
pendingAction = PendingAction.NONE;
} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
handlePendingAction();
}
updateUI();
}
private void updateUI() {
Session session = Session.getActiveSession();
boolean enableButtons = (session != null && session.isOpened());
if (enableButtons && user1 != null) {
// profilePictureView.setProfileId(user.getId());
// greeting.setText(getString(R.string.app_name, user.getFirstName()));
} else {
// profilePictureView.setProfileId(null);
// greeting.setText(null);
}
}
@SuppressWarnings("incomplete-switch")
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but
// we assume they
// will succeed.
pendingAction = PendingAction.NONE;
}
在OnCreate:
In the onCreate:
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
if (savedInstanceState != null) {
name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
//===============================================
Session.openActiveSessionFromCache(getActivity());
//================================================
这是我的Facebook帖子的方法,我称之为一个按钮点击,这是一个列表视图:
This is my facebook post method, I call this on a button click, which is in a listview:
public void postFB(String id) {
System.out.println("in fb");
if (isNetworkConnected()) {
Session session = Session.getActiveSession();
if (session != null) {
System.out.println("session not null");
if (hasPublishPermission()) {
//do something
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
getActivity(), Session.openActiveSessionFromCache(getActivity()),
params)).setOnCompleteListener(
new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
// frag3.setFbId(null);
// ---------------------------- got to put
// check here
// onBackPressed();
}
}).build();
feedDialog.show();
} else if (session.isOpened()) {
// We need to get new permissions, then complete the action
// when we get called back.
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
getActivity(), PERMISSION));
// do something
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(
getActivity(), Session.getActiveSession(),
params)).setOnCompleteListener(
new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
// frag3.setFbId(null);
// ---------------------------- got to put
// check here
//onBackPressed();
}
}).build();
feedDialog.show();
}
}else if(session == null){
System.out.println("login");
}
} else {
Toast.makeText(getActivity(),
"Please check your internet connection", Toast.LENGTH_LONG)
.show();
}
}
然而,这并不在我看来,一个正确的做法,有没有更好的办法?另外我如何检测,如果用户会话已过期,并提示用户重新登录?该文档不似乎显示登录按钮的内部运作?
This however does not seem to me a correct approach, is there any better way? Also how do I detect if the user session is expired and prompt the user to login again? The Docs dont seem to reveal the internal functioning of the Login button?
推荐答案
- 添加Facebook SDK在您的项目
-
添加以下线路在AndroidManifest.xml中下标签
- Add the facebook SDK in your project
Add below lines in AndroidManifest.xml under tag
<activity android:name="com.facebook.LoginActivity" />
-
另外添加Facebook应用程序ID在string.xml
Also Add facebook app id in string.xml
声明私有成员
private boolean isOnCreate; private List<String> permissions = new ArrayList<String>(); private JSONObject facebookObject; private ProgressDialog progressDialog; /** The callback. */ private final com.facebook.Session.StatusCallback callback = new com.facebook.Session.StatusCallback() { @Override public void call(Session session, SessionState state, Exception exception) { SignInActivity.this.onSessionStateChange(session, state, exception); } }; private void onSessionStateChange(Session session, SessionState state, Exception exception) { if (state == SessionState.OPENED) { if (this.isOnCreate) { this.isOnCreate = false; return; } onFacebookLoginDone(); } else if (state == SessionState.CLOSED_LOGIN_FAILED) { showErrorMessage(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Session session = Session.getActiveSession(); if (session == null) { session = new Session(this); session.closeAndClearTokenInformation(); } Session.setActiveSession(session); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_fb_login: this.loginUsingFacebook(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); } /** * Login using facebook. */ private void loginUsingFacebook() { isOnCreate = false; final Session session = Session.getActiveSession(); if (session != null && session.getState().equals(SessionState.OPENED)) { Session.openActiveSession(this, true, this.callback); onFacebookLoginDone(); } else { final Session.OpenRequest temp = new Session.OpenRequest(this); this.permissions.clear(); this.permissions.add(UserClass.EMAIL); this.permissions.add("user_location"); temp.setPermissions(this.permissions); temp.setCallback(this.callback); session.openForRead(temp); } } /** * On facebook login done. */ private void onFacebookLoginDone() { final Bundle bundle = new Bundle(); bundle.putString("fields", "first_name,last_name,id,location,locale,username,email,verified"); new PerformSignUpOnServer("/me", bundle).execute(); } /** * The Class PerformSignUpOnServer. */ private class PerformSignUpOnServer extends AsyncTask<Void, Void, Void> { /** The server url. */ private String serverURL; /** The server bundle. */ private Bundle serverBundle; /** * Instantiates a new perform sign up on server. * * @param url * the url * @param bundle * the bundle */ public PerformSignUpOnServer(String url, Bundle bundle) { this.serverBundle = bundle; this.serverURL = url; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPreExecute() */ @Override protected void onPreExecute() { progressDialog = ProgressDialog.show(SignInActivity.this, "", "Loading..."); super.onPreExecute(); } /* * (non-Javadoc) * * @see android.os.AsyncTask#doInBackground(Params[]) */ @Override protected Void doInBackground(Void... params) { signUpUserOnServer(this.serverURL, this.serverBundle); return null; } /* * (non-Javadoc) * * @see android.os.AsyncTask#onPostExecute(java.lang.Object) */ @Override protected void onPostExecute(Void result) { } } /** * Sign up user on server. * * @param url * the url * @param bundle * the bundle */ private void signUpUserOnServer(String url, Bundle bundle) { final Session session = Session.getActiveSession(); if (session != null && session.isClosed() == false) { final Request userInformation = new Request(session, url, bundle, HttpMethod.GET); final Response response = userInformation.executeAndWait(); facebookObject = response.getGraphObject().getInnerJSONObject(); Log.d("json", facebookObject.toString()); } } /** * On session state change. * * @param state * the state */ private void onSessionStateChange(SessionState state) { if (state == SessionState.OPENED) { if (isOnCreate) { isOnCreate = false; return; } onFacebookLoginDone(); } }
请参阅您的日志猫标签JSON,你将有一个Facebook对象
See your log cat with tag "json" you will have a facebook object
这篇关于正确使用Facebook登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!