How do we send GIF image which is present in asset folder to another application using Intent?
I have tried this:
private File getEmojiFile(int position) {
AssetManager assetManager = getApplicationContext().getAssets();
File file = new File(getCacheDir(), mEmojiFileNames[position]);
try {
if (!file.createNewFile()) {
//Emoji File already exists.
return file;
}
} catch (IOException e) {
e.printStackTrace();
}
FileChannel in_chan = null, out_chan = null;
try {
AssetFileDescriptor in_afd = assetManager.openFd(mEmojiFileNames[position]);
FileInputStream in_stream = in_afd.createInputStream();
in_chan = in_stream.getChannel();
FileOutputStream out_stream = new FileOutputStream(file);
out_chan = out_stream.getChannel();
in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
} catch (IOException ioe) {
Log.w("copyFileFromAssets", "Failed to copy file '" + mEmojiFileNames[position] + "' to external storage:" + ioe.toString());
} finally {
try {
if (in_chan != null) {
in_chan.close();
}
if (out_chan != null) {
out_chan.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return file;
}
and then sending it to another app using Intent:
final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EMOJI_IMAGE_TYPE emojiImageType = getImageType(position);
intent.setType("image/gif"));
intent.setPackage(getCurrentAppPackage(SoftKeyboard.this, getCurrentInputEditorInfo()));
PackageManager packageManager = getPackageManager();
if (intent.resolveActivity(packageManager) != null) {
//Save emoji file because current input field supports GIF/PNG.
File emojiFile = getEmojiFile(position);
Uri photoURI = FileProvider.getUriForFile(SoftKeyboard.this, SoftKeyboard.this.getApplicationContext().getPackageName() + ".provider", emojiFile);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
dialog.dismiss();
hideWindow();
try {
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(SoftKeyboard.this,"This text field does not support "+
"GIF"+" insertion from the keyboard.",Toast.LENGTH_LONG).show();
}
However, after this blank image is coming. Here is tried to send the image to messenger application. It accepted intent but showed blank transparent image:
Scenario: You have a gif file in the Drawable Folder.
Then the code will be:`
private void shareDrawable(Context context,int resourceId,String fileName) {
try {
//create an temp file in app cache folder
File outputFile = new File(context.getCacheDir(), fileName + ".gif");
FileOutputStream outPutStream = new FileOutputStream(outputFile);
//Saving the resource GIF into the outputFile:
InputStream is = getResources().openRawResource(resourceId);
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int current = 0;
while ((current = bis.read()) != -1) {
baos.write(current);
}
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(baos.toByteArray());
//
outPutStream.flush();
outPutStream.close();
outputFile.setReadable(true, false);
//share file
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(outputFile));
shareIntent.setType("image/gif");
context.startActivity(shareIntent);
}
catch (Exception e) { Toast.makeText(context, "error", Toast.LENGTH_LONG);}
}
Related
I want to share .gif from my app to facebook,gmail.
hello there is any way to share gif image
i have gif in drawable folder ("giphy.gif")
below are code that i have try , but it give me error.(no attached file)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shareGif("giphy");
}
private void shareGif(String resourceName) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "giphy.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024 * 500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
}
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then you have to save the gif to external storage, and finally load that file.
try {
CopyRAWtoSDCard(mContext,R.drawable.giphy, "giphy");
} catch (IOException e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/yourapp/giphy.gif");
it.setType("image/*");
it.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
it.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.app_name));
it.putExtra(Intent.EXTRA_TEXT, "Gif attached");
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent in = Intent.createChooser(it,"Share");
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(in);
private void CopyRAWtoSDCard(Context mContext,int id,String name) throws IOException {
String path = Environment.getExternalStorageDirectory() + "/yourapp";
File dir = new File(path);
if (dir.mkdirs() || dir.isDirectory()) {
try {
InputStream in = mContext.getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path+ File.separator + name+".gif");
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();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Works like a Charm!
I have to open pdf file stored in asset folder. When I am trying to open the file in Android 6, it shows error. But, no problem with other android versions. I think its the problem with permission. Please help to rectify this error.
Here is my code
....
dialBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + email+".pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + email+".pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(getApplicationContext(), "Please install any pdf reader App.",
Toast.LENGTH_LONG).show();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.adobe.reader")));
}
}
});
}
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase(email+".pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
Did you included: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
and: <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> in the manifest?
Also I have found this code:
public class SampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CopyReadAssets();
}
private void CopyReadAssets()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "abc.pdf");
try
{
in = assetManager.open("abc.pdf");
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e)
{
Log.e("tag", e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(
Uri.parse("file://" + getFilesDir() + "/abc.pdf"),
"application/pdf");
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
Here is the link of another answer: Read a pdf file from assets folder
We are working on android application,in which mp3 files should be downloaded into internal storage in a background service. We have implemented this using with code snippet mentioned below inside an intent service,But when we try to play the mp3 we are getting an error,like player is not supporting this audio file. If any one has a solution for this issue,Please advise me for the same.
Code Snippet:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
// String fileName = Environment.getExternalStorageDirectory().toString() + "/trail.mp3";
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
//URL url = new URL(urlPath);
InputStream input = new BufferedInputStream(url.openStream());
stream = url.openConnection().getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
byte data[] = new byte[lenghtOfFile];
long total = 0;
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
// Successful finished
result = Activity.RESULT_OK;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
publishResults(output.getAbsolutePath(), result);
}
1.Check if urlPath is correct.You can open it by explorer and check if a .mp3 begins to be downloaded.
2.Compare size of the file that you get by explorer to the one that downloaded through your code.
3.If the sizes differ,that means download failure.Try to modify your code like this:
String urlPath = intent.getStringExtra(URL);
String fileName = intent.getStringExtra(FILENAME);
File output = new File(Environment.getExternalStorageDirectory(),
fileName);
File dir = new File(output.getAbsolutePath()
+ "/TRIALS/");
dir.mkdirs();
String path = dir + "/" +"trail" + ".mp3";
File f = new File(path);
if (f.exists()) {
f.delete();
}
InputStream stream = null;
FileOutputStream fos = null;
try {
URL url = new URL(urlPath);
URLConnection urlcon = url.openConnection();
stream = urlcon.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
fos = new FileOutputStream(f.getPath());
int times = -1;
while ((times = reader.read()) != -1) {
fos.write(times);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I remove some useless code and add fos.flush() before fos.close().
I am using share intent in my application,but i am not able to share image and text,i am using image and text from my json response,but it is not working.i am not getting any error,but the the method for sharing is not working
JSON Response : http://pastie.org/10753346
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri(descpic);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, desc.getText().toString());
shareIntent.setType("image/*");
// Launch sharing dialog for image
startActivity(Intent.createChooser(shareIntent, "Share Image"));
} else {
// ...sharing failed, handle error
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
/*Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}*/
OutputStream fOut = null;
Uri outputFileUri=null;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File sdImageMainDirectory = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(sdImageMainDirectory);
fOut = new FileOutputStream(sdImageMainDirectory);
} catch (Exception e) {
Toast.makeText(this, "Error occured. Please try again later.",
Toast.LENGTH_SHORT).show();
}
try {
bmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
}
return outputFileUri;
}
Do this to save image. Replace your method with this
public Uri getLocalBitmapUri(ImageView imageView) {
imageview.buildDrawingCache();
Bitmap bm = imageview.getDrawingCache();
OutputStream fOut = null;
Uri outputFileUri;
try {
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "folder_name" + File.separator);
root.mkdirs();
File imageFile = new File(root, "myPicName.jpg");
outputFileUri = Uri.fromFile(imageFile);
fOut = new FileOutputStream(imageFile);
} catch (Exception e) {
e.printStackTrace();
}
try {
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.flush();
fOut.close();
return outputFileUri;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
My app uses the following piece of code to write out images I have resized into the app's data folder:
private void writeImage(Bitmap bmp, String filename)
{
try
{
FileOutputStream stream = openFileOutput(filename, MODE_WORLD_WRITEABLE);
bmp.compress(CompressFormat.PNG, 100, stream);
stream.flush();
stream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
I am able to read them in a file browser (ddms) and can confirm they appear to have been written.
However, any attempt to load the images results in non-null bitmaps with width and height of -1. I am using the following code to load them:
imageList = getFilesDir().list();
Bitmap bmp = null;
for(String img : imageList)
{
try {
bmp = BitmapFactory.decodeStream(openFileInput(img));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT: On further inspection, it seems, after conversion the images are of density 160 (and not 240 as they should be) also, after testing a working application it seems the -1 mWidth and -1 mHeight on the bitmaps is irrelevent.
I had same problem.my data folder given smallest image.and cursor return null pointer exception on my getDestination method.then i fixed like it
public void captureNewPhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
targetFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
targetUri = Uri.fromFile(targetFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targetUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 12);
}
And i use like in onActivityResult();
BitmapFactory.Options options = new BitmapFactory.Options();
networkBitmap = BitmapFactory.decodeFile(targetUri.getPath(),
options);
//ImageDialog(networkBitmap);
//String path = getRealPathFromUri(this, Uri.parse(targetUri.getPath()));
String myDeviceModel = android.os.Build.MODEL;
deviceName = Build.MANUFACTURER;
if (myDeviceModel.equals("GT-I9500")) {
} else if (deviceName.contains("samsung")) {
} else {
exif = ReadExif(targetUri.getPath());
if (exif.equals("6")) {
matrixx.postRotate(90);
} else if (exif.equals("7")) {
matrixx.postRotate(-90);
} else if (exif.equals("8")) {
matrixx.postRotate(-90);
} else if (exif.equals("5")) {
matrixx.postRotate(-90);
}
//matrixx.postRotate(-90);
}
networkBitmap = Bitmap.createBitmap(networkBitmap, 0, 0, networkBitmap.getWidth(), networkBitmap.getHeight(), matrixx, true);
Log.e("Taget File ", "Size " + targetFile.length());
if (networkBitmap != null) {
ImageSetting(networkBitmap, System.currentTimeMillis() + filename);
}
public void ImageSetting(Bitmap imageBitmap, final String fileName) {
networkBitmap = imageBitmap;
organizator(networkBitmap, fileName);
networkBitmap = null;
}` public void tamamlandiOndenFoto(Bitmap turnedBitmap, String filename) {
frontFotoFile = storeBitmap(networkBitmap, filename);
ondenFotoPath = ondenFoto.getAbsolutePath();
ondenFotoImageView.setImageBitmap(turnedBitmap);
}`
public File storeBitmap(Bitmap bp, String fileName) {
File sd = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File dest = new File(sd, fileName);
if (bp != null) {
try {
FileOutputStream out = new FileOutputStream(dest);
bp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Alinan hata ", " Catch hata ", e);
}
return dest;
} else {
return null;
}
}
I hope give you any idea for your problem.