ACTION_VIEW intent for a file with unknown MimeType

后端 未结 13 1804
抹茶落季
抹茶落季 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:42

    You should always check the same with

    PackageManager packageManager = getActivity().getPackageManager();
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent);
    } else {
        Log.d(TAG, "No Intent available to handle action");
    
    }
    

    and to get MimeTpye of file you can use :-

     public String getMimeType(Uri uri, Context context) {
            String mimeType = null;
            if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
                ContentResolver cr = context.getContentResolver();
                mimeType = cr.getType(uri);
            } else {
                String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
                        .toString());
                mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
                        fileExtension.toLowerCase());
            }
            return mimeType;
        }
    

提交回复
热议问题