美文网首页简化开发
适配AndroidQ,调用手机自带软件,通过Uri打开相应文件,

适配AndroidQ,调用手机自带软件,通过Uri打开相应文件,

作者: wenju | 来源:发表于2021-05-17 13:56 被阅读0次
public static void openUri(Context context,Uri uri){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        String mimeType=getMimeType(context,uri);
        intent.setDataAndType(uri,mimeType);
        context.startActivity(Intent.createChooser(intent,"Select browse tool"));
        }

public static String getMimeType(Context context,Uri uri){
        String mimeType=parseMimeType(context,uri);
        if(TextUtils.isEmpty(mimeType)){
        mimeType=queryMimeType(context.getContentResolver(),uri);
        }

        return mimeType;
        }

private static String queryMimeType(ContentResolver contentResolver,Uri uri){
        String mimeType="";
        String[]projections=new String[]{"mime_type"};
        Cursor cursor=null;

        try{
        cursor=contentResolver.query(uri,projections,(String)null,(String[])null,(String)null);
        if(cursor==null){
        LogUtils.e("getMimeType get a empty cursor: "+uri.toString());
        }else if(cursor.moveToFirst()){
        mimeType=cursor.getString(cursor.getColumnIndexOrThrow("mime_type"));
        }
        }catch(Exception var9){
        var9.printStackTrace();
        }finally{
        if(cursor!=null){
        cursor.close();
        }

        }

        return mimeType;
        }


private static String parseMimeType(Context context,Uri uri){
        String mimeType="";
        MediaMetadataRetriever metadataRetriever=null;

        try{
        metadataRetriever=new MediaMetadataRetriever();
        metadataRetriever.setDataSource(context,uri);
        mimeType=metadataRetriever.extractMetadata(12);
        }catch(Exception var8){
        var8.printStackTrace();
        }finally{
        if(metadataRetriever!=null){
        metadataRetriever.release();
        }

        }

        return mimeType;
        }
        ```

相关文章

网友评论

    本文标题:适配AndroidQ,调用手机自带软件,通过Uri打开相应文件,

    本文链接:https://www.haomeiwen.com/subject/dedjjltx.html