I have next situation.
I get file from bytesArray, build file from it, and wonna view this file from other application.
- File builds correctly (I can see that from file system)
- I can open that file through file system and it openes correctly.
- 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!
UPDATE
If someone looking for working example, here some code changes you need to do:
Uri fileUri = getUriForFile(getApplicationContext(), "com.myapp.packadge.fileprovider", outputFile);
intent.setDataAndType(fileUri, mime);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
AndroidManifest.xml
<application
....
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.myApp.packadge.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
filepath.xml
<paths>
<files-path path="internalStorage/outputDir/" name="reports" />
</paths>