open a pdf file programmatically

后端 未结 7 2119
广开言路
广开言路 2021-01-06 15:45

I am working on pdf. I am trying to open a pdf file from my application using the code below. But I failed to open.

private void openPdf() {

        File fi         


        
7条回答
  •  不思量自难忘°
    2021-01-06 15:53

    for android 9 and 10 you should use this code

    1-create one class

    public class GenericFileProvider extends FileProvider {
    
    }
    

    2-in res directory create one directory to name of xml and create one file to name of provider_paths.xml and add this code

    
        
    
    

    3-in manifests in application add this code

      
          
      
    

    4-you should get Permission Manifest.permission.READ_EXTERNAL_STORAGE

    5-and add this codes

    String fileName="yourfile.pdf";
    
    File file = new File(Environment.getExternalStorageDirectory()+"/Android/data/ir.tdaapp.paymanyar/files/File",fileName);
    
    String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
    
    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    
    Intent intent = new Intent(Intent.ACTION_VIEW);
    
    intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK);
    
    Uri uri = FileProvider.getUriForFile(getContext(), getActivity().getApplicationContext().getPackageName() + ".provider", file);
    
    intent.setDataAndType(uri, mimeType);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    
    startActivity(Intent.createChooser(intent, "choseFile"));
    

    6-I suggest you add this code to the application in manifests

    android:requestLegacyExternalStorage="true"
    

提交回复
热议问题