ACTION_VIEW intent for a file with unknown MimeType

后端 未结 13 1800
抹茶落季
抹茶落季 2020-11-27 10:57

My app has a feature that browse files on your phone and SD card and open them using other apps. I want a solution where I don\'t have to specify the MimeType and can work w

13条回答
  •  执笔经年
    2020-11-27 11:59

    This will work surely..

     private void showFile(File file, String filetype) 
    {
                    MimeTypeMap myMime = MimeTypeMap.getSingleton();
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String mimeType = 
                    myMime.getMimeTypeFromExtension(filetype);
                    if(android.os.Build.VERSION.SDK_INT >=24) {
                     Uri fileURI = FileProvider.getUriForFile(getContext(),
                                BuildConfig.APPLICATION_ID + ".provider",
                                file);
                        intent.setDataAndType(fileURI, mimeType);
    
                    }else {
                        intent.setDataAndType(Uri.fromFile(file), mimeType);
                    }
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    try {
                        context.startActivity(intent);
                    }catch (ActivityNotFoundException e){
                        Toast.makeText(context, "No Application found to open this type of file.", Toast.LENGTH_LONG).show();
    
                    }
                }
    

提交回复
热议问题