Android Image sending intent - android

i am trying to share an image from the drawables in my application. i keep getting java.io.FileNotFoundException:/abc.jpg (read-only file system)
my code is
private String SaveCache(int resID) {
String path = "";
try {
InputStream is = getResources().openRawResource(resID);
File cacheDir = this.getExternalCacheDir();
File downloadingMediaFile = new File(cacheDir, "abc.jpg");
byte[] buf = new byte[256];
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
while (true) {
int rd = is.read(buf, 0, 256);
if (rd == -1 || rd == 0)
break;
out.write(buf, 0, rd);
}
is.close();
out.close();
return downloadingMediaFile.getPath();
} catch (Exception ex) {
Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
return path;
}
private void ImageShare() {
String path = SaveCache(R.drawable.testsend);
Toast.makeText(this, path, Toast.LENGTH_LONG).show();
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_SUBJECT, "test");
share.putExtra(Intent.EXTRA_TEXT, "test");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + path));
try {
startActivity(Intent.createChooser(share, "Choose share method."));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Any help is appreciated, if more info is required i will be happy to provide.

Make sure that the external storage is mounted.
From the docs of getExternalCacheDir():
Returns the path of the directory holding application cache files on
external storage. Returns null if external storage is not currently
mounted so it could not ensure the path exists; you will need to call
this method again when it is available.

http://www.anddev.org/post3469.html#p3469
You need to use
FileOutputStream fos = openFileOutput(name, MODE);
as mentioned in the example.

Related

Sending GIF image in asset folder to another application using Intent

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);}
}

share apk from my app doesnt work

i want to share my apllication's apk to another device, and this is not working.
this code is from the internet.. how can i fix this and share my app from my app
private void shareApplication() {
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
Intent intent = new Intent(Intent.ACTION_SEND);
// MIME of .apk is "application/vnd.android.package-archive".
// but Bluetooth does not accept this. Let's use "*/*" instead.
intent.setType("*/*");
// Append file and send Intent
File originalApk = new File(filePath);
try {
//Make new directory in new location
File tempFile = new File(getExternalCacheDir() + "/ExtractedApk");
//If directory doesn't exists create new
if (!tempFile.isDirectory())
if (!tempFile.mkdirs())
return;
//Get application's name and convert to lowercase
tempFile = new File(tempFile.getPath() + "/" + getString(app.labelRes).replace(" ","").toLowerCase() + ".apk");
//If file doesn't exists create new
if (!tempFile.exists()) {
if (!tempFile.createNewFile()) {
return;
}
}
//Copy file to new location
InputStream in = new FileInputStream(originalApk);
OutputStream out = new FileOutputStream(tempFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
System.out.println("File copied.");
//Open share dialog
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tempFile));
startActivity(Intent.createChooser(intent, "Share app via"));
} catch (IOException e) {
e.printStackTrace();
}
}
it`s send the apk in same weight as the generating of android atudio but when install the app crash.

prevent storing a video file twice in internal storage in android

how to prevent storing same file selected in galary twice in internal storage in android .I tried with below code it copies same video many times in a folder in the internal storage .
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
new SaveVideoInFolder().execute(uri);
try {
InputStream is = getContentResolver().openInputStream(uri);
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, "video_choosing");
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
file = new File(app_directory, filename);
Toast.makeText(MainActivity.this,file.toString(),Toast.LENGTH_SHORT).show();
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Log.e("TAG", "File Not Found", e);
} catch (IOException e) {
Log.e("TAG", "IOException", e);
}
}
// Create the storage directory if it does not exist
if (!file.exists()) {
if (!file.mkdirs()) {
/* Log.e(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");*/
return null;
}
only you have check that your file is exist bt if condition and make directory if it is not..
File file = new File(app_directory, filename);
if(file.exists()){
...
}
else {
...
}

Getting a video from Google Photos returns an empty file

I'm working on an application that allows the user to import videos and edit them. The applications allows the user to import local videos, or videos from Google Photos or Drive. The following code was working
Intent i = new Intent();
i.setType("video/mp4");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_CODE);
and then, on the onActivityResult method, I copy to file from Photos or Drive
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
File storage = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
File app_directory = new File(storage, APP_NAME);
if (!app_directory.exists())
app_directory.mkdirs();
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String filename = String.format("VID_%s.mp4", timestamp);
File file = new File(app_directory, filename);
InputStream is = getContentResolver().openInputStream(uri);
OutputStream output = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int read;
while ((read = is.read(buffer)) != -1)
output.write(buffer, 0, read);
output.flush();
output.close();
} catch (FileNotFoundException e) {
Toast.makeText(this, "File Not Found", Toast.LENGTH_LONG).show();
Log.e(TAG, "File Not Found", e);
} catch (IOException e) {
Toast.makeText(this, "Could not save the file", Toast.LENGTH_LONG).show();
Log.e(TAG, "IOException", e);
}
}
However since the latest update of the Google Photos app I'm only getting very small file that I cannot open with any application, and sometimes for oldest videos I'm getting a FileNotFoundException
I have tried a couple of solutions, like changing the intent to request the file like this
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("video/mp4");
startActivityForResult(i, REQUEST_CODE);
or getting the InputStream through a FileDescriptor
ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
InputStream is = new FileInputStream(fileDescriptor);
With the same result

Sending picture in Whatsapp

I want to send a picture in Whatsapp. My App starts when I select the Image chooser in Whatsapp. How can I send the result of the Intent back to whatsapp?
I use the following Code:
// on button press
String path = SaveCache(R.drawable.pic_1);
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + path));
}
}
private String SaveCache(int resID) {
String path = "";
try {
InputStream is = getResources().openRawResource(resID);
File cacheDir = context.getExternalCacheDir();
File downloadingMediaFile = new File(cacheDir, "abc.jpg");
byte[] buf = new byte[256];
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
while (true) {
int rd = is.read(buf, 0, 256);
if (rd == -1 || rd == 0)
break;
out.write(buf, 0, rd);
}
is.close();
out.close();
return downloadingMediaFile.getPath();
} catch (Exception ex) {
ex.printStackTrace();
}
return path;
}
I was able to send image using this code
Uri uri = Uri.parse("android.resource://com.example.test/drawable/image_1");
sharingIntent.setType("image/jpg");
sharingIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));

Categories

Resources