0

In my app i download pdf file from url and open this pdf with chooser. The opened file canot be shared.

This is the code i used to open pdf files.

File file = new File(Environment.getExternalStoragePublicDirectory(                Environment.DIRECTORY_DOWNLOADS).toString()+"/oferte/oferta"+insertedid+".pdf");
File(getApplicationContext().getFilesDir().toString()+"/oferta"+idfactura+".pdf");
       Intent target = new Intent(Intent.ACTION_VIEW);
       target.setDataAndType(Uri.fromFile(file),"application/pdf");
       target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
       Intent intent = Intent.createChooser(target, "Open File");
       try {
           startActivity(intent);
           finish();
       } catch (ActivityNotFoundException e) {

       }
cvmircea
  • 31
  • 1
  • 10

1 Answers1

0

First app must has READ_EXTERNAL_STORAGE permission.Runtime requests (Android 6.0 and higher). link https://developer.android.com/training/permissions/requesting.html

And from android N share file to other app must use FileProvider。

edit manifest xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
        ...>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${appPackageName}.fileprovider"
            android:grantUriPermissions="true"
            android:exported="false">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/filepaths" />
        </provider>
        ...
    </application>
</manifest>

res/xml/filepaths.xml

<paths>
    <files-path path="files/" name="myfiles" />
</paths>

share file

    Intent target = new Intent(Intent.ACTION_VIEW);
    Uri fileUri;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        fileUri = FileProvider.getUriForFile(this,
                "appPackageName.fileprovider", file);
        target.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        target.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    } else {
        fileUri = Uri.fromFile(file);
    }
    target.setDataAndType(fileUri,"application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
    Intent intent = Intent.createChooser(target, "Open File");
    try {
        startActivity(intent);
        finish();
    } catch (ActivityNotFoundException e) {
    }

link https://developer.android.com/training/secure-file-sharing/setup-sharing https://stackoverflow.com/a/38858040/4696538

fancyyou
  • 965
  • 6
  • 7