Friday 19 June 2015

To share image to facebook twitter

Android async process  for sharing a image thru share intent

To share image  to facebook twitter and other share intents we have to download the image as a temp file and use it
//Use the async task on click


shareAsynctask task = new shareAsynctask();

task.execute();


shareAsynctask 

ProgressDialog pd
@SuppressWarnings("unused")
private class shareAsynctask extends AsyncTask<String, Void, String> {
File file;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub

super.onPreExecute();

pd = new ProgressDialog(yourActivity.this);
pd.setMessage("loading");
pd.show();

}

@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Bitmap bbicon = null;
String Url;

if (null != image_url) {

bbicon = getBitmapFromURL(image_url);

} else {

bbicon = getBitmapFromURL(image_url);
}
;// BitmapFactory.decodeResource(getResources(),R.drawable.bannerd10);
String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
OutputStream outStream = null;
file = new File(extStorageDirectory, "temp.png");
try {
outStream = new FileOutputStream(file, false);
bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
}
return "";

}

@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
share.putExtra(Intent.EXTRA_SUBJECT, "subject");
share.putExtra(Intent.EXTRA_TEXT, "body");
startActivityForResult(Intent.createChooser(share, "Share Image"),
0);
pd.show();

}



}

// Get the bitmap from the below function

public static Bitmap getBitmapFromURL(String src) {

    try {
   
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
System.out.println(Uri.encode(src,"UTF-8"));
        URL url = new URL(src.replaceAll(" ", "%20"));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        //pDialog.dismiss();
        return myBitmap;
    } catch (IOException e) {

        e.printStackTrace();
        return null;
    }
   
}



No comments:

Post a Comment