Skip to content

Instantly share code, notes, and snippets.

@harshadura
Created January 30, 2015 08:30
Show Gist options
  • Save harshadura/d4d309fa8394ffbfcc48 to your computer and use it in GitHub Desktop.
Save harshadura/d4d309fa8394ffbfcc48 to your computer and use it in GitHub Desktop.
Facebook opengraph test
/**
* @author Harsha Siriwardena
*
*/
public class SharingBaseActivity extends Activity {
public Spinner sharingSpinner;
String SD_CARD_PATH = null;
public static String FACEBOOK_TITLE = "";
public static String FACEBOOK_DESC = "";
public static String FACEBOOK_ACTION_LINK = "";
public static String FACEBOOK_ACTION_LINK_URL = "";
public static String NAMESPACE_PROPERTY_FB_OPENGRAPH = "";
public static String PROPERTY_FB_OPENGRAPH_OBJECT = "";
public static String PROPERTY_FB_OPENGRAPH_ACTION = "";
public static String PROPERTY_FB_OPENGRAPH_OBJECT_TYPE = "";
public static String PROPERTY_FB_OPENGRAPH_ACTION_TYPE = "";
public static int share_image_id;
public static String share_image_url = null;
public static Bitmap bitmap_image = null;
public static String fb_image_url = null;
File casted_image = null;
Button btn;
public static boolean isWeatherDog = false;
private static final String TAG = "SharingBaseActivity";
private TwitterSharing twitterObj = null;
// Set to true to upload an image to the staging
// resource before creating the Open Graph object.
static final boolean UPLOAD_IMAGE = true;
private ProgressDialog progressDialog;
private Activity mContext = null;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback = new Session.StatusCallback() {
@Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
@Override
protected void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null && (session.isOpened() || session.isClosed())) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
@Override
protected void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
if (pendingPublishReauthorization && state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
}
}
}
/*
* Helper method to check a collection for a string.
*/
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate...");
mContext = this;
SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
Bundle bundle = getIntent().getExtras();
if (bundle != null)
share_image_id = bundle.getInt("SHARE_IMAGE_ID");
if (bundle != null)
share_image_url = bundle.getString("SHARE_IMAGE_URL");
FACEBOOK_TITLE = getResources().getString(R.string.msg_share_facebook_title);
FACEBOOK_DESC = getResources().getString(R.string.msg_share_facebook_desc);
FACEBOOK_ACTION_LINK = getResources().getString(R.string.msg_share_facebook_action_link);
FACEBOOK_ACTION_LINK_URL = getResources().getString(R.string.msg_share_facebook_action_link_url);
NAMESPACE_PROPERTY_FB_OPENGRAPH = getResources().getString(R.string.fbopengraph_namespace);
// PROPERTY_FB_OPENGRAPH_OBJECT = getResources().getString(R.string.weatherdog_property_fbopengraph_object);
// PROPERTY_FB_OPENGRAPH_ACTION = getResources().getString(R.string.weatherdog_property_fbopengraph_action);
PROPERTY_FB_OPENGRAPH_OBJECT_TYPE = NAMESPACE_PROPERTY_FB_OPENGRAPH + ":" + PROPERTY_FB_OPENGRAPH_OBJECT;
PROPERTY_FB_OPENGRAPH_ACTION_TYPE = NAMESPACE_PROPERTY_FB_OPENGRAPH + ":" + PROPERTY_FB_OPENGRAPH_ACTION;
TWITTER_TWEET = getResources().getString(R.string.msg_share_twitter_tweet);
INSTAGRAM_CAPTION = getResources().getString(R.string.msg_share_instagram_caption);
EMAIL_BODY = getResources().getString(R.string.msg_share_email_body);
EMAIL_SUBJECT = getResources().getString(R.string.msg_share_email_subject);
if (savedInstanceState != null) {
pendingPublishReauthorization = savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
}
protected void fbShare() {
Session.openActiveSession(SharingBaseActivity.this, true, new Session.StatusCallback() {
// callback when session changes state
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
if (!session.isPermissionGranted("publish_actions")) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(SharingBaseActivity.this, "publish_actions"));
}
// Post image status
// postImageToFacebook();
//
// OR do post ordinary status ..
String imagePath = "";
if (fb_image_url == null) {
imagePath = getResources().getString(R.string.url_pink_fb_share_image);
} else {
imagePath = fb_image_url;
}
publishFeedDialog(FACEBOOK_TITLE, FACEBOOK_TITLE, FACEBOOK_DESC, FACEBOOK_ACTION_LINK_URL, imagePath);
}
}
});
}
private void displayAlertDialogForOpenGraphSharings(String title, String msg, String leftbutton, String rightbutton, Boolean isWithFbApp) {
if (msg.length() > 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(SharingBaseActivity.this);
if (title.length() > 0)
builder.setTitle(title);
builder.setCancelable(false);
builder.setMessage(msg);
builder.setPositiveButton(leftbutton, null);
if (isWithFbApp == null) {
if (rightbutton != null) {
builder.setNegativeButton(rightbutton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
fbShare();
}
});
}
} else if (isWithFbApp == true) {
if (rightbutton != null) {
builder.setNegativeButton(rightbutton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
fbShareOpenGraphStory_withFBApp();
}
});
}
} else if (isWithFbApp == false) {
if (rightbutton != null) {
builder.setNegativeButton(rightbutton, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
fbShareOpenGraphStory();
}
});
}
}
try {
builder.create().show();
} catch (Exception e) {
Log.e(TAG, "Error", e);
}
}
}
private void fbShareOpenGraphStory_withFBApp() {
// Session session = Session.getActiveSession();
Session.openActiveSession(SharingBaseActivity.this, true, new Session.StatusCallback() {
// callback when session changes state
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
if (!session.isPermissionGranted("publish_actions")) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(SharingBaseActivity.this, "publish_actions"));
}
if (session != null) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(mContext, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
OpenGraphObject fbGraphObject = OpenGraphObject.Factory.createForPost(PROPERTY_FB_OPENGRAPH_OBJECT_TYPE);
fbGraphObject.setProperty("title", FACEBOOK_TITLE);
fbGraphObject.setProperty("url", FACEBOOK_ACTION_LINK_URL);
fbGraphObject.setProperty("description", FACEBOOK_DESC);
List<Bitmap> images = new ArrayList<Bitmap>();
if (share_image_id == 0) {
images.add(bitmap_image);
} else {
Bitmap image = BitmapFactory.decodeResource(mContext.getResources(), share_image_id);
images.add(image);
}
OpenGraphAction fbGraphAction = GraphObject.Factory.create(OpenGraphAction.class);
fbGraphAction.setType(PROPERTY_FB_OPENGRAPH_ACTION_TYPE);
fbGraphAction.setProperty(PROPERTY_FB_OPENGRAPH_OBJECT, fbGraphObject);
FacebookDialog shareDialog2 = new FacebookDialog.OpenGraphActionDialogBuilder(mContext, fbGraphAction, PROPERTY_FB_OPENGRAPH_OBJECT)
.setImageAttachmentsForObject(PROPERTY_FB_OPENGRAPH_OBJECT, images, false).build();
uiHelper.trackPendingDialogCall(shareDialog2.present());
}
}
}
});
}
private void fbShareOpenGraphStory() {
// Un-comment the line below to turn on debugging of requests
// Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);
// Session session = Session.getActiveSession();
// if (session == null) {
Session.openActiveSession(SharingBaseActivity.this, true, new Session.StatusCallback() {
// callback when session changes state
public void call(final Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// if (!session.isPermissionGranted("publish_actions")) {
// session.requestNewPublishPermissions(new Session.NewPermissionsRequest(SharingBaseActivity.this, "publish_actions"));
// }
if (session != null) {
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(mContext, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
// Show a progress dialog because the batch
// request could take a while.
progressDialog = ProgressDialog.show(SharingBaseActivity.this, "",
SharingBaseActivity.this.getResources().getString(R.string.msg_share_facebook_opengraph_share_progress), true);
// progressDialog =
// ProgressDialog.show(mContext, "",
// "Sharing to Facebook, please wait.", true);
try {
// Create a batch request, firstly to post a
// new object and
// secondly to publish the action with the
// new object's id.
RequestBatch requestBatch = new RequestBatch();
// Request: Staging image upload request
// --------------------------------------------
// If uploading an image, set up the first
// batch request
// to do this.
if (UPLOAD_IMAGE) {
// Set up image upload request
// parameters
Bundle imageParams = new Bundle();
Bitmap image = null;
if (share_image_id == 0) {
image = bitmap_image;
} else {
image = BitmapFactory.decodeResource(mContext.getResources(), share_image_id);
}
imageParams.putParcelable("file", image);
// Set up the image upload request
// callback
Request.Callback imageCallback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
// Log any response error
FacebookRequestError error = response.getError();
if (error != null) {
dismissProgressDialog();
Log.i(TAG, error.getErrorMessage());
}
}
};
// Create the request for the image
// upload
Request imageRequest = new Request(Session.getActiveSession(), "me/staging_resources", imageParams, HttpMethod.POST,
imageCallback);
// Set the batch name so you can refer
// to the result
// in the follow-on object creation
// request
imageRequest.setBatchEntryName("imageUpload");
// Add the request to the batch
requestBatch.add(imageRequest);
}
// Request: Object request
// --------------------------------------------
// Set up the JSON representing the book
JSONObject fbGraphObjectJson = new JSONObject();
// publishFeedDialog(FACEBOOK_TITLE,
// FACEBOOK_TITLE,
// FACEBOOK_DESC, FACEBOOK_ACTION_LINK_URL,
// imagePath);
//
// Set up the book image
if (UPLOAD_IMAGE) {
// Set the book's image from the "uri"
// result from
// the previous batch request
fbGraphObjectJson.put("image", "{result=imageUpload:$.uri}");
} else {
fbGraphObjectJson.put("image", SharingBaseActivity.this.getResources().getString(R.string.url_pink_fb_share_image));
}
fbGraphObjectJson.put("title", FACEBOOK_TITLE);
fbGraphObjectJson.put("url", FACEBOOK_ACTION_LINK_URL);
fbGraphObjectJson.put("description", FACEBOOK_DESC);
// JSONObject data = new JSONObject();
// data.put("isbn", "0-553-57340-3");
// book.put("data", data);
// Set up object request parameters
Bundle objectParams = new Bundle();
objectParams.putString("object", fbGraphObjectJson.toString());
// Set up the object request callback
Request.Callback objectCallback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
// Log any response error
FacebookRequestError error = response.getError();
if (error != null) {
dismissProgressDialog();
Log.i(TAG, error.getErrorMessage());
}
}
};
// Create the request for object creation
Request objectRequest = new Request(Session.getActiveSession(), "me/objects/" + PROPERTY_FB_OPENGRAPH_OBJECT_TYPE, objectParams,
HttpMethod.POST, objectCallback);
// Set the batch name so you can refer to
// the result
// in the follow-on publish action request
objectRequest.setBatchEntryName("objectCreate");
// Add the request to the batch
requestBatch.add(objectRequest);
// Request: Publish action request
// --------------------------------------------
Bundle actionParams = new Bundle();
// Refer to the "id" in the result from the
// previous batch request
// this object is the associated object
// name, can be: book
actionParams.putString(PROPERTY_FB_OPENGRAPH_OBJECT, "{result=objectCreate:$.id}");
// Turn on the explicit share flag
actionParams.putString("fb:explicitly_shared", "true");
// Set up the action request callback
Request.Callback actionCallback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
dismissProgressDialog();
FacebookRequestError error = response.getError();
if (error != null) {
// Toast.makeText(getApplicationContext(),
// "Error posting story to Facebook",
// Toast.LENGTH_LONG).show();
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", false);
Log.e(TAG, error.getErrorMessage());
Log.e(TAG, "Error posting story to Facebook", error.getException());
return;
} else {
String actionId = null;
try {
GraphObject graphRes = response.getGraphObject();
JSONObject graphResponse = null;
try {
graphResponse = graphRes.getInnerJSONObject();
actionId = graphResponse.getString("id");
} catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "Error posting story to Facebook",
// Toast.LENGTH_LONG).show();
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close",
"Try again", false);
Log.e(TAG, "Error " + e.getMessage());
Log.e(TAG, "Error posting story to Facebook", e);
return;
}
} catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "Error posting story to Facebook",
// Toast.LENGTH_LONG).show();
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again",
false);
Log.e(TAG, "Error " + e.getMessage());
Log.e(TAG, "Error posting story to Facebook", e);
return;
}
if (isWeatherDog) {
displayAlertDialogForOpenGraphSharings("All set!", "We posted your Weather Mini Dog love on Facebook.", "OK", null,
false);
} else {
displayAlertDialogForOpenGraphSharings("All set!", "Posted to Facebook.", "OK", null, false);
}
// Toast.makeText(getApplicationContext(),
// "Successfully published to Facebook",
// Toast.LENGTH_LONG).show();
Log.v(TAG, "Successfully published OpenGraph story to Facebook: Action Id: " + actionId);
}
}
};
// Create the publish action request
Request actionRequest = new Request(Session.getActiveSession(), "me/" + PROPERTY_FB_OPENGRAPH_ACTION_TYPE, actionParams,
HttpMethod.POST, actionCallback);
// Add the request to the batch
requestBatch.add(actionRequest);
// Execute the batch request
requestBatch.executeAsync();
} catch (Exception e) {
// Toast.makeText(getApplicationContext(),
// "Error posting story to Facebook",
// Toast.LENGTH_LONG).show();
Log.e(TAG, "Error " + e.getMessage());
Log.e(TAG, "Error posting story to Facebook", e);
dismissProgressDialog();
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", false);
}
}
}
}
});
// }
}
/*
* Helper method to dismiss the progress dialog.
*/
private void dismissProgressDialog() {
// Dismiss the progress dialog
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
// uiHelper.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
@Override
public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
Log.e("Activity", String.format("Error: %s", error.toString()));
error.printStackTrace();
}
@Override
public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
String gesture = FacebookDialog.getNativeDialogCompletionGesture(data);
Log.v(TAG, "Facebook Post response --- " + gesture);
if (gesture != null) {
if ("post".equals(gesture)) {
if(isWeatherDog){
displayAlertDialogForOpenGraphSharings("All set!", "We posted your Weather Mini Dog love on Facebook.", "OK", null, true);
}
else{
displayAlertDialogForOpenGraphSharings("All set!", "Posted to Facebook.", "OK", null, null);
}
// the user hit Post
} else if ("cancel".equals(gesture)) {
// if(isWeatherDog){
// displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again", "Close", "Try again", true);
// }
// else{
// displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again", "Close", "Try again", null);
// }
// the user hit cancel
} else {
if(isWeatherDog){
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", true);
}
else{
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", null);
}
// unknown value
}
} else {
if(isWeatherDog){
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", true);
}
else{
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", null);
}
// either an error occurred, or your app has never been authorized
}
}
});
}
private void publishFeedDialog(String name, String caption, String description, String link, String urlPicture) {
Bundle params = new Bundle();
params.putString("name", name);
params.putString("caption", caption);
params.putString("description", description);
params.putString("link", link);
params.putString("picture", urlPicture);
Session session = Session.getActiveSession();
WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(SharingBaseActivity.this, session, params)).setOnCompleteListener(new OnCompleteListener() {
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) {
// listenerShareFacebook.onShareFacebookSuccess();
displayAlertDialogForOpenGraphSharings("All set!", "Posted to Facebook.", "OK", null, null);
// Toast.makeText(getApplicationContext(),
// "Successfully published to Facebook",
// Toast.LENGTH_LONG).show();
} else {
// User clicked the Cancel button
// Toast.makeText(getApplicationContext(),
// "Facebook Publish cancelled",
// Toast.LENGTH_LONG).show();
// displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again", "Close", "Try again", null);
// listenerShareFacebook.onShareFacebookFailure("Publish cancelled");
}
} else if (error instanceof FacebookOperationCanceledException) {
// Toast.makeText(getApplicationContext(),
// "Facebook Publish cancelled", Toast.LENGTH_LONG).show();
// displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", null);
// User clicked the "x" button
// listenerShareFacebook.onShareFacebookFailure("Publish cancelled");
} else {
// Toast.makeText(getApplicationContext(),
// "Error posting story to Facebook",
// Toast.LENGTH_LONG).show();
displayAlertDialogForOpenGraphSharings("Oops!", "We couldn't post on Facebook. Try again.", "Close", "Try again", null);
// Generic, ex: network error
// listenerShareFacebook.onShareFacebookFailure("Error posting story");
}
}
}).build();
feedDialog.show();
}
public Uri getImageUriByBitmapObj(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "PINK", null);
return Uri.parse(path);
}
private void sendTweetViaNativeApp(String text, Uri uri) {
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setClassName("com.twitter.android", "com.twitter.android.composer.ComposerActivity");
intent.putExtra(Intent.EXTRA_TEXT, text);
if (uri != null) {
intent.putExtra(Intent.EXTRA_STREAM, uri);
}
startActivity(intent);
} catch (final Exception e) {
// Errors tested: ActivityNotFoundException, java.lang.SecurityException
this.runOnUiThread(new Runnable() {
public void run() {
Log.v(TAG, "Problem connecting to the installed version of Twitter, Redirecting to PINK's embedded Twitter view.." + e.getMessage());
displayAlertDialogForTwitterSharings("Oops!", "We couldn't post on Twitter. There seems to have a problem with the current installed version of Twitter App, Please update it or try again with Twitter Fallback interface", "Close", "Try again");
}
});
}
}
public boolean isPackageExisted(String targetPackage) {
List<ApplicationInfo> packages;
PackageManager pm;
pm = getPackageManager();
packages = pm.getInstalledApplications(0);
for (ApplicationInfo packageInfo : packages) {
if (packageInfo.packageName.equals(targetPackage))
return true;
}
return false;
}
public void setupImageForSharing(){
if (share_image_id == 0 && share_image_url != null) {
URL url;
try {
url = new URL(share_image_url);
casted_image = new File(url.toURI());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// new File(share_image_url);
} else if (share_image_id != 0) {
castImageIdToFile();
} else if (share_image_id == 0 && share_image_url == null && bitmap_image != null) {
castBitmapToFile();
}
else {
share_image_id = R.drawable.ui_image_share_instagram;
castImageIdToFile();
}
}
public void castImageIdToFile() {
try {
InputStream in = getResources().openRawResource(share_image_id);
FileOutputStream out = new FileOutputStream(SD_CARD_PATH + "/pink_temp_tweet.png");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
casted_image = new File(SD_CARD_PATH + "/pink_temp_tweet.png");
} catch (Exception e) {
e.printStackTrace();
}
}
public void castBitmapToFile() {
try {
// Convert bitmap to byte array
Bitmap bitmap = bitmap_image;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream out = new FileOutputStream(SD_CARD_PATH + "/pink_temp_tweet.png");
try {
out.write(bitmapdata);
} finally {
out.close();
}
casted_image = new File(SD_CARD_PATH + "/pink_temp_tweet.png");
} catch (Exception e) {
e.printStackTrace();
}
}
public static byte[] readFile(File file) throws IOException {
// Open file
RandomAccessFile f = new RandomAccessFile(file, "r");
try {
// Get and check length
long longlength = f.length();
int length = (int) longlength;
if (length != longlength)
throw new IOException("File size >= 2 GB");
// Read file and return data
byte[] data = new byte[length];
f.readFully(data);
return data;
} finally {
f.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment