Skip to content

Instantly share code, notes, and snippets.

@JChudasama
Created August 11, 2015 16:32
Show Gist options
  • Save JChudasama/f7153026babf3c41110f to your computer and use it in GitHub Desktop.
Save JChudasama/f7153026babf3c41110f to your computer and use it in GitHub Desktop.
public class FbHelper {
private Context mContext;
private Activity mActivity;
public static final String POST_SUCESS = "post_sucess";
public static final String POST_FAIL = "post_fail";
public static final String POST_LOGIN_NOTFOUND = "post_login_notfound";
private Bundle savedInstanceState;
private String message = "";
private String name = "";
private String caption = "";
private String link = "";
private String pictureLink = "";
private byte[] pictureArray = null;
private String description = "";
private Bitmap image;
private GraphUser user;
private static final String MESSAGE_SUCCESS = "Successfully posted on wall.";
private static final String MESSAGE_FAIL = "Failed to post on wall.";
private ProgressDialog progressDialog;
private void dismissProgressDialog()
{
try
{
progressDialog.dismiss();
} catch (Exception e)
{
// TODO: handle exception
}
}
private boolean isInitLoginCall = false;
public interface FacebookHelperListerner
{
void onComplete(String message);
}
private FacebookHelperListerner facebookHelperListerner;
public void setFBHelperListerner(FacebookHelperListerner facebookHelperListerner)
{
this.facebookHelperListerner = facebookHelperListerner;
}
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions", "read_stream", "email", "user_about_me");
//"friends_about_me", "friends_notes"
private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
private Session.StatusCallback statusCallback = new SessionStatusCallback();
private enum PendingAction
{
NONE, POST_PHOTO, POST_STATUS_UPDATE, POST_STATUS_PHOTO, POST_LINK
}
private PendingAction pendingAction = PendingAction.NONE;
public FbHelper(Context context)
{
mContext = context;
initHelper();
}
public FbHelper(Activity activity)
{
mActivity = activity;
mContext = mActivity;
initHelper();
}
public FbHelper(Activity activity, Bundle savedInstanceState)
{
mContext = activity;
this.savedInstanceState = savedInstanceState;
initHelper();
}
private void initHelper()
{
progressDialog = new ProgressDialog(mContext);
progressDialog.setTitle("Facebook");
progressDialog.setMessage("Please wait...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
Session session = Session.getActiveSession();
if (session == null)
{
if (savedInstanceState != null)
{
session = Session.restoreSession(mContext, null, statusCallback, savedInstanceState);
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
if (session == null)
{
session = new Session(mContext);
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED))
{
isInitLoginCall = true;
//login();
}
}
}
private Session getActiveSession()
{
Session session = Session.getActiveSession();
if (session == null)
{
session = new Session(mContext);
}
Session.setActiveSession(session);
return session;
}
private class SessionStatusCallback implements Session.StatusCallback
{
@Override
public void call(Session session, SessionState state, Exception exception)
{
onSessionStateChange(session, state, exception);
// fetchUserInfo();
Log.i("log_tag", "call state: " + state);
if (state == SessionState.OPENED)
{
// facebookHelperListerner.onSessionStatusCall(session, state, exception);
facebookHelperListerner.onComplete(Global.LOGIN_SUCESS);
}
if (state == SessionState.CLOSED)
{
facebookHelperListerner.onComplete(Global.LOGOUT_SUCESS);
}
if (state == SessionState.CLOSED_LOGIN_FAILED)
{
logout();
facebookHelperListerner.onComplete(Global.LOGIN_ABORT_ERROR);
}
}
}
private void onSessionStateChange(Session session, SessionState state, Exception exception)
{
if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException))
{
new AlertDialog.Builder(mContext).setTitle("Canceled").setMessage("Unable to perform selected action because permissions were not granted.")
.setPositiveButton("OK", null).show();
pendingAction = PendingAction.NONE;
}
else if (state == SessionState.OPENED_TOKEN_UPDATED)
{
handlePendingAction();
}
}
public boolean isLogin()
{
Session session = getActiveSession();
if (!session.isOpened() && !session.isClosed())
{
return false;
}
else
{
return true;
}
}
public void login()
{
Session session = getActiveSession();
String sdkVerion=Settings.getSdkVersion();
Log.d("SDK version",sdkVerion);
// SessionState state = session.getState();
// state = SessionState.CREATED;
if (!session.isOpened() && !session.isClosed())
{
Log.e("log_tag", "openForRead");
Session.OpenRequest openRequest = new Session.OpenRequest(mActivity);
openRequest.setCallback(statusCallback);
openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
//openRequest.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
//openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);
openRequest.setPermissions(PERMISSIONS);
session.openForPublish(openRequest);
}
else
{
Log.e("log_tag", "openActiveSession");
Session.openActiveSession(mActivity, true, statusCallback);
}
}
public void logout()
{
Session session = getActiveSession();
if (session != null)
{
session.closeAndClearTokenInformation();
Session.setActiveSession(null);
Logger.i("Facebook Logout successfully");
}
// if (!session.isClosed())
// {
// session.closeAndClearTokenInformation();
// }
}
public void onStart()
{
try
{
getActiveSession().addCallback(statusCallback);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onStop()
{
try
{
getActiveSession().removeCallback(statusCallback);
} catch (Exception e){
e.printStackTrace();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.e("log_tag", "onActivityResult: ");
getActiveSession().onActivityResult(mActivity, requestCode, resultCode, data);
}
public void onSavedInstanceState(Bundle outState)
{
Session session = getActiveSession();
Session.saveSession(session, outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
public void postPictureAndStatus(String msg, String mCaption, byte[] picArray)
{
if (TextUtils.isEmpty(msg)){
try {
msg = JsonParsing.getStartupAttribute(JSONKEYS.RADIO.KEY_SHARE_FB);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Log.e("log_tag", "Posting picture and status\n" + msg);
message = msg;
caption = mCaption;
pictureArray = picArray;
pendingAction = PendingAction.POST_STATUS_PHOTO;
performPublish();
}
private void postPictureAndStatus()
{
if (user != null && hasPublishPermission())
{
progressDialog.show();
Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
Bundle postParams = new Bundle();
postParams.putString("caption", "");
postParams.putByteArray("picture", byteArrayImage);
postParams.putString("message",Global.SHARING_MESSAGE);
Request.Callback callback = new Request.Callback()
{
public void onCompleted(Response response)
{
progressDialog.dismiss();
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try
{
postId = graphResponse.getString("id");
} catch (JSONException e)
{
Log.i("log_tag", "JSON error " + e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null)
{
Toast.makeText(mContext.getApplicationContext(), error.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(mContext.getApplicationContext(), "Successfully posted", Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(getActiveSession(), "me/photos", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
else
{
pendingAction = PendingAction.POST_STATUS_PHOTO;
}
}
private void publishFeedDialog() {
Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
Bundle postParams = new Bundle();
postParams.putString("name", "Fluid stream");
postParams.putString("caption", "");
postParams.putString("description",message);
postParams.putByteArray("picture", byteArrayImage);
postParams.putString("link", "https://developers.facebook.com/android");
/*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");*/
WebDialog feedDialog = (
new WebDialog.FeedDialogBuilder(mActivity,
Session.getActiveSession(),
postParams))
.setOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(Bundle values,
FacebookException error) {
if (error == null) {
// When the story is posted, echo the success
// and the post Id.
final String postId = values.getString("post_id");
if (postId != null) {
Toast.makeText(mActivity,mContext.getString(R.string.success_fb),Toast.LENGTH_SHORT).show();
} else {
// User clicked the Cancel button
Toast.makeText(mActivity.getApplicationContext(), mContext.getString(R.string.fb_publish_cancel), Toast.LENGTH_SHORT).show();
}
} else if (error instanceof FacebookOperationCanceledException) {
// User clicked the "x" button
Toast.makeText(mActivity.getApplicationContext(), mContext.getString(R.string.fb_publish_cancel), Toast.LENGTH_SHORT).show();
} else {
// Generic, ex: network error
Toast.makeText(mActivity.getApplicationContext(), mContext.getString(R.string.fb_publish_error), Toast.LENGTH_SHORT).show();
}
logout();
}
})
.build();
feedDialog.show();
}
public boolean hasPublishPermission()
{
Session session = getActiveSession();
return session != null && session.getPermissions().contains("publish_actions");
}
public void getMyDetails()
{
Log.e("log_tag", "getMyDetails " + hasPublishPermission());
Session session = getActiveSession();
if (session != null)
{
// if (hasPublishPermission())
// {
// We can do the action right away.
if (user == null)
{
Request request = Request.newMeRequest(session, new Request.GraphUserCallback()
{
@Override
public void onCompleted(GraphUser me, Response response)
{
// if (currentSession ==
// sessionTracker.getOpenSession()) {
user = me;
OrigzoPreferences.getInstance().storeFBUserDetail(user);
Log.d("FB_USERID", user.getId());
Log.d("FB_FNAME", user.getFirstName());
Log.d("FB_LNAME", user.getLastName());
// Log.e("log_tag", "GraphUser onCompleted");
// Log.e("log_tag", "response: " + response.toString());
handlePendingAction();
// }
// if (response.getError() != null) {
// Log.e("log_tag",
// "Error: "+response.getError());
// }
}
});
Request.executeBatchAsync(request);
}
else
{
Log.d("FB_USERID", user.getId());
Log.d("FB_FNAME", user.getFirstName());
Log.d("FB_LNAME", user.getLastName());
OrigzoPreferences.getInstance().storeFBUserDetail(user);
//handlePendingAction();
}
// }
// else
// {
// // We need to get new permissions, then complete the action when
// // we get called back.
// // session.requestNewPublishPermissions(new
// Session.NewPermissionsRequest(mActivity, PERMISSIONS));
// }
}
else
{
facebookHelperListerner.onComplete(POST_LOGIN_NOTFOUND);
}
}
private void performPublish()
{
Log.e("log_tag", "performPublish " + hasPublishPermission());
Session session = getActiveSession();
if (session != null)
{
// if (hasPublishPermission())
// {
// We can do the action right away.
if (user == null)
{
Request request = Request.newMeRequest(session, new Request.GraphUserCallback()
{
@Override
public void onCompleted(GraphUser me, Response response)
{
// if (currentSession ==
// sessionTracker.getOpenSession()) {
user = me;
Log.e("log_tag", "GraphUser onCompleted");
Log.e("log_tag", "response: " + response.toString());
handlePendingAction();
// }
// if (response.getError() != null) {
// Log.e("log_tag",
// "Error: "+response.getError());
// }
}
});
Request.executeBatchAsync(request);
}
else
{
handlePendingAction();
}
// }
// else
// {
// // We need to get new permissions, then complete the action when
// // we get called back.
// // session.requestNewPublishPermissions(new
// Session.NewPermissionsRequest(mActivity, PERMISSIONS));
// }
}
else
{
facebookHelperListerner.onComplete(POST_LOGIN_NOTFOUND);
}
}
@SuppressWarnings("incomplete-switch")
private void handlePendingAction()
{
Log.e("log_tag", "handlePendingAction");
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but
// we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction)
{
case POST_STATUS_PHOTO:
// postPictureAndStatus();
publishFeedDialog();
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment