You can find full source code on GitHub.
I am trying to make custom helper for integrate Facebook API in android project please check below file for facebook helper class:
Please check below class to access FacebookHelper class in your activity:
Please don't miss to add AndroidMenifect.xml entries.
You can find full source code on GitHub.
I am trying to make custom helper for integrate Facebook API in android project please check below file for facebook helper class:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kal.fbshare; | |
import java.io.ByteArrayOutputStream; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.MalformedURLException; | |
import java.util.Arrays; | |
import java.util.List; | |
import org.json.JSONException; | |
import org.json.JSONObject; | |
import android.app.Activity; | |
import android.app.AlertDialog; | |
import android.app.ProgressDialog; | |
import android.content.Intent; | |
import android.graphics.Bitmap; | |
import android.os.Bundle; | |
import android.os.Environment; | |
import android.util.Log; | |
import android.widget.Toast; | |
import com.facebook.FacebookAuthorizationException; | |
import com.facebook.FacebookOperationCanceledException; | |
import com.facebook.FacebookRequestError; | |
import com.facebook.HttpMethod; | |
import com.facebook.LoggingBehavior; | |
import com.facebook.Request; | |
import com.facebook.RequestAsyncTask; | |
import com.facebook.Response; | |
import com.facebook.Session; | |
import com.facebook.SessionDefaultAudience; | |
import com.facebook.SessionLoginBehavior; | |
import com.facebook.SessionState; | |
import com.facebook.Settings; | |
import com.facebook.android.AsyncFacebookRunner; | |
import com.facebook.android.FacebookError; | |
import com.facebook.model.GraphUser; | |
import com.facebook.widget.WebDialog; | |
public class FacebookHelper | |
{ | |
private Activity mActivity; | |
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."; | |
public interface FacebookHelperListerner | |
{ | |
void onSessionStatusCall(Session session, SessionState state, Exception exception); | |
} | |
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","upload_video"); | |
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 FacebookHelper(Activity activity) | |
{ | |
mActivity = activity; | |
initHelper(); | |
} | |
public void publishFeedDialog() | |
{ | |
try | |
{ | |
Bundle params = new Bundle(); | |
params.putString("name", "Facebook SDK for Android");// title | |
params.putString("caption", "Build great social apps and get more installs.");// caption | |
params.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps."); | |
params.putString("picture", "https://developer.android.com/images/brand/en_generic_rgb_wo_45.png"); | |
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(mActivity, Session.getActiveSession(), params)).setOnCompleteListener(null).build(); | |
feedDialog.show(); | |
} catch (Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
} | |
public FacebookHelper(Activity activity, Bundle savedInstanceState) | |
{ | |
mActivity = activity; | |
this.savedInstanceState = savedInstanceState; | |
initHelper(); | |
} | |
private void initHelper() | |
{ | |
Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); | |
Session session = Session.getActiveSession(); | |
if (session == null) | |
{ | |
if (savedInstanceState != null) | |
{ | |
session = Session.restoreSession(mActivity, null, statusCallback, savedInstanceState); | |
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY); | |
pendingAction = PendingAction.valueOf(name); | |
} | |
if (session == null) | |
{ | |
session = new Session(mActivity); | |
} | |
Session.setActiveSession(session); | |
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) | |
{ | |
login(); | |
} | |
} | |
} | |
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); | |
} | |
} | |
} | |
private void onSessionStateChange(Session session, SessionState state, Exception exception) | |
{ | |
if (pendingAction != PendingAction.NONE && (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) | |
{ | |
new AlertDialog.Builder(mActivity).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 void login() | |
{ | |
Session session = Session.getActiveSession(); | |
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.setPermissions(PERMISSIONS); | |
session.openForPublish(openRequest); | |
} | |
else | |
{ | |
Log.e("log_tag", "openActiveSession"); | |
Session.openActiveSession(mActivity, true, statusCallback); | |
} | |
} | |
public void logout() | |
{ | |
Session session = Session.getActiveSession(); | |
session.close(); | |
if (!session.isClosed()) | |
{ | |
session.closeAndClearTokenInformation(); | |
} | |
} | |
public void postVideo() | |
{ | |
final ProgressDialog progressDialog=ProgressDialog.show(mActivity, "", "Uploading..."); | |
File file=new File(Environment.getExternalStorageDirectory()+"/baby_fart.3gp"); | |
try { | |
Request audioRequest = Request.newUploadVideoRequest(Session.getActiveSession(), file, new Request.Callback() { | |
@Override | |
public void onCompleted(Response response) { | |
// TODO Auto-generated method stub | |
if(response.getError()==null) | |
{ | |
Log.e("log_tag", "Video Shared Successfully"); | |
Toast.makeText(mActivity, "Video Shared Successfully", Toast.LENGTH_SHORT).show(); | |
} | |
else | |
{ | |
Log.e("log_tag", ""+response.getError().getErrorMessage()); | |
Toast.makeText(mActivity, response.getError().getErrorMessage(), Toast.LENGTH_SHORT).show(); | |
} | |
try | |
{ | |
progressDialog.dismiss(); | |
}catch (Exception e) { | |
// TODO: handle exception | |
} | |
} | |
}); | |
audioRequest.executeAsync(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
public void onStart() | |
{ | |
Session.getActiveSession().addCallback(statusCallback); | |
} | |
public void onStop() | |
{ | |
Session.getActiveSession().removeCallback(statusCallback); | |
} | |
public void onActivityResult(int requestCode, int resultCode, Intent data) | |
{ | |
Log.e("log_tag", "onActivityResult: "); | |
Session.getActiveSession().onActivityResult(mActivity, requestCode, resultCode, data); | |
} | |
public void onSavedInstanceState(Bundle outState) | |
{ | |
Session session = Session.getActiveSession(); | |
Session.saveSession(session, outState); | |
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name()); | |
} | |
public void getFriendList() | |
{ | |
// Request.executeMyFriendsRequestAsync(Session.getActiveSession(), new Request.GraphUserListCallback() | |
// { | |
// | |
// @Override | |
// public void onCompleted(List<GraphUser> users, Response response) | |
// { | |
// Log.d("Friends Length", "" + users.size()); | |
// for (int i = 0; i < users.size(); i++) | |
// { | |
// GraphUser graphUser = users.get(i); | |
// Log.e("log_tag", "jason: " + graphUser.getInnerJSONObject()); | |
// } | |
// | |
// } | |
// }); | |
Request friendRequest = Request.newMyFriendsRequest(Session.getActiveSession(), new Request.GraphUserListCallback() | |
{ | |
@Override | |
public void onCompleted(List<GraphUser> users, Response response) | |
{ | |
// for (int i = 0; i < users.size(); i++) | |
// { | |
// GraphUser graphUser=users.get(i); | |
// Log.e("log_tag", "jason: "+graphUser.getInnerJSONObject()); | |
// graphUser.getProperty(""); | |
// } | |
Log.e("log_tag", "Jason: " + users.toString()); | |
} | |
}); | |
Bundle params = new Bundle(); | |
params.putString("fields", "id,name, birthday, email"); | |
friendRequest.setParameters(params); | |
friendRequest.executeAsync(); | |
// String fqlQuery = "SELECT uid, name, pic_square, contact_email FROM user WHERE uid IN " + "(SELECT uid2 FROM friend WHERE uid1 = me())"; | |
// Bundle params = new Bundle(); | |
// params.putString("q", fqlQuery); | |
// Session session = Session.getActiveSession(); | |
// Request request = new Request(session, "/fql", params, HttpMethod.GET, new Request.Callback() | |
// { | |
// public void onCompleted(Response response) | |
// { | |
// Log.e("log_tag", "response: "+response); | |
// } | |
// }); | |
// Request.executeBatchAsync(request); | |
} | |
public void postStatusUpdate(String msg) | |
{ | |
message = msg; | |
pendingAction = PendingAction.POST_STATUS_UPDATE; | |
performPublish(); | |
} | |
private void postStatusUpdate() | |
{ | |
Log.e("log_tag", "postStatusUpdate: " + message); | |
if (user != null && hasPublishPermission()) | |
{ | |
Request request = Request.newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() | |
{ | |
@Override | |
public void onCompleted(Response response) | |
{ | |
Log.e("log_tag", "Error: " + response.getError()); | |
FacebookRequestError frError = response.getError(); | |
if (frError != null) | |
{ | |
showToast(frError.getErrorMessage().substring(frError.getErrorMessage().lastIndexOf(")") + 1)); | |
} | |
else | |
{ | |
showToast("Sucessfully Posted!"); | |
} | |
logout(); | |
Log.d("log_tag", "GraphObject: " + response.getGraphObject()); | |
} | |
}); | |
request.executeAsync(); | |
} | |
else | |
{ | |
pendingAction = PendingAction.POST_STATUS_UPDATE; | |
} | |
} | |
public void postLink(String mMessage, String mName, String mCaption, String mDescription, String mLink, String picLink) | |
{ | |
message = mMessage; | |
name = mName; | |
caption = mCaption; | |
description = mDescription; | |
link = mLink; | |
pictureLink = picLink; | |
Log.e("log_tag", "Posting link.."); | |
pendingAction = PendingAction.POST_LINK; | |
performPublish(); | |
} | |
private void postLinkWithImage() | |
{ | |
if (user != null && hasPublishPermission()) | |
{ | |
Bundle postParams = new Bundle(); | |
postParams.putString("message", message); | |
postParams.putString("name", name); | |
postParams.putString("caption", caption); | |
postParams.putString("description", description); | |
postParams.putString("link", link); | |
postParams.putString("picture", pictureLink); | |
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("log_tag", "JSON error " + e.getMessage()); | |
} | |
FacebookRequestError error = response.getError(); | |
if (error != null) | |
{ | |
Toast.makeText(mActivity.getApplicationContext(), MESSAGE_FAIL + " " + error.getErrorMessage(), Toast.LENGTH_SHORT).show(); | |
} | |
else | |
{ | |
Toast.makeText(mActivity.getApplicationContext(), MESSAGE_SUCCESS, Toast.LENGTH_LONG).show(); | |
} | |
logout(); | |
} | |
}; | |
Request request = new Request(Session.getActiveSession(), "100002152179898/feed", postParams, HttpMethod.POST, callback); | |
RequestAsyncTask task = new RequestAsyncTask(request); | |
task.execute(); | |
} | |
else | |
{ | |
pendingAction = PendingAction.POST_LINK; | |
} | |
} | |
public void postPictureAndStatus(String msg, String mCaption, byte[] picArray) | |
{ | |
Log.e("log_tag", "Posting picture and status"); | |
message = msg; | |
caption = mCaption; | |
pictureArray = picArray; | |
pendingAction = PendingAction.POST_STATUS_PHOTO; | |
performPublish(); | |
} | |
private void postPictureAndStatus() | |
{ | |
if (user != null && hasPublishPermission()) | |
{ | |
// 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", caption); | |
postParams.putByteArray("picture", pictureArray); | |
postParams.putString("message", message); | |
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("log_tag", "JSON error " + e.getMessage()); | |
} | |
FacebookRequestError error = response.getError(); | |
if (error != null) | |
{ | |
Toast.makeText(mActivity.getApplicationContext(), error.getErrorMessage(), Toast.LENGTH_SHORT).show(); | |
} | |
else | |
{ | |
Toast.makeText(mActivity.getApplicationContext(), postId, Toast.LENGTH_LONG).show(); | |
} | |
} | |
}; | |
Request request = new Request(Session.getActiveSession(), "me/photos", postParams, HttpMethod.POST, callback); | |
RequestAsyncTask task = new RequestAsyncTask(request); | |
task.execute(); | |
} | |
else | |
{ | |
pendingAction = PendingAction.POST_STATUS_PHOTO; | |
} | |
} | |
protected void showToast(String string) | |
{ | |
// TODO Auto-generated method stub | |
Toast.makeText(mActivity, string, Toast.LENGTH_SHORT).show(); | |
} | |
public void postPhoto(Bitmap bitmap) | |
{ | |
this.image = bitmap; | |
pendingAction = PendingAction.POST_PHOTO; | |
performPublish(); | |
} | |
private void postPhoto() | |
{ | |
if (hasPublishPermission()) | |
{ | |
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(), image, new Request.Callback() | |
{ | |
@Override | |
public void onCompleted(Response response) | |
{ | |
Log.e("log_tag", "Error: " + response.getError()); | |
Log.d("log_tag", "GraphObject: " + response.getGraphObject()); | |
} | |
}); | |
request.executeAsync(); | |
} | |
else | |
{ | |
pendingAction = PendingAction.POST_PHOTO; | |
} | |
} | |
private boolean hasPublishPermission() | |
{ | |
Session session = Session.getActiveSession(); | |
return session != null && session.getPermissions().contains("publish_actions"); | |
} | |
private void performPublish() | |
{ | |
Log.e("log_tag", "performPublish " + hasPublishPermission()); | |
Session 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)); | |
// } | |
} | |
} | |
@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_PHOTO: | |
postPhoto(); | |
break; | |
case POST_STATUS_UPDATE: | |
postStatusUpdate(); | |
break; | |
case POST_STATUS_PHOTO: | |
postPictureAndStatus(); | |
case POST_LINK: | |
postLinkWithImage(); | |
} | |
} | |
} |
Please check below class to access FacebookHelper class in your activity:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.kal.myfacebookdemo_3_1; | |
import android.app.Activity; | |
import android.content.Intent; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.view.View.OnClickListener; | |
import android.widget.Button; | |
import com.facebook.Session; | |
import com.facebook.SessionState; | |
import com.kal.fbshare.FacebookHelper; | |
import com.kal.fbshare.FacebookHelper.FacebookHelperListerner; | |
public class MainActivity extends Activity | |
{ | |
Button btnLogin; | |
FacebookHelper fbHelper; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) | |
{ | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
fbHelper = new FacebookHelper(MainActivity.this); | |
fbHelper.setFBHelperListerner(new FacebookHelperListerner() | |
{ | |
@Override | |
public void onSessionStatusCall(Session session, SessionState state, Exception exception) | |
{ | |
afterLoginSuccess(); | |
} | |
}); | |
btnLogin = (Button) findViewById(R.id.btnLogin); | |
btnLogin.setOnClickListener(new OnClickListener() | |
{ | |
@Override | |
public void onClick(View v) | |
{ | |
// TODO Auto-generated method stub | |
shareViaFacebook(); | |
} | |
}); | |
} | |
private void shareViaFacebook() | |
{ | |
Session session = Session.getActiveSession(); | |
if (!session.isOpened()) | |
{ | |
fbHelper.login(); | |
} | |
else | |
{ | |
// fbHelper.getFriendList(); | |
afterLoginSuccess(); | |
} | |
} | |
private void afterLoginSuccess() | |
{ | |
// Please add you action after login facebook here.... | |
} | |
@Override | |
public void onStart() | |
{ | |
super.onStart(); | |
fbHelper.onStart(); | |
} | |
@Override | |
public void onStop() | |
{ | |
super.onStop(); | |
fbHelper.onStop(); | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) | |
{ | |
super.onActivityResult(requestCode, resultCode, data); | |
fbHelper.onActivityResult(requestCode, resultCode, data); | |
} | |
@Override | |
protected void onSaveInstanceState(Bundle outState) | |
{ | |
super.onSaveInstanceState(outState); | |
fbHelper.onSavedInstanceState(outState); | |
} | |
} |
Please don't miss to add AndroidMenifect.xml entries.
You can find full source code on GitHub.
No comments:
Post a Comment