uniq uniq - 9 months ago 29
Java Question

Files doesnt shows its conent if they called from MyApp to view in other App



I have next situation.
I get file from bytesArray, build file from it, and wonna view this file from other application.


  1. File builds correctly (I can see that from file system)

  2. I can open that file through file system and it openes correctly.

  3. If I try to view this file from my app through other app I get some unexpected cases.



For example:

I use image/jpg, and wonna view it through google photo, and app showes me black screen, and if i try to use some app action (image info), app crashes.

File file, outputFile = null;
String fileName;
if(android.os.Environment.getExternalStorageState()
.equals(android.os.Environment.MEDIA_MOUNTED)) {
file = new File(Environment.getExternalStorageDirectory(), ".MyApp/Files/");
if (!file.exists()) {
file.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
fileName = "report_" + sdf.format(new Date());
outputFile = new File(file.getAbsolutePath() + "/" + fileName + finalExtention);
}
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
fileOutputStream.write(bytes);
fileOutputStream.close();
Intent intent = new Intent();
String mime = getMimeType(outputFile.getAbsolutePath());
String filePath = outputFile.getAbsolutePath();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(filePath), mime);
Intent intentChooser = Intent.createChooser(intent, "Choose an application to open with:");
startActivity(intentChooser);




getMimeType return String like "image/jpeg"

finalExtension gets from json (for this case ".jpg")



My AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />




What I see from MyApp:
From MyApp

What I see from File System: From File System

Searching for help, guys. No idea what I'm doing wrong with intents.

Thanks!

Answer Source

In newer versions of Android it has been changed. Now you have to define provider in your manifest file to let another appliactions access your files: https://developer.android.com/training/secure-file-sharing/setup-sharing.html and https://developer.android.com/reference/android/support/v4/content/FileProvider.html.

It has been also answered on stackoverflow: How to use support FileProvider for sharing content to other apps?