首页 > 其他分享 >使用Android自带文件选择器

使用Android自带文件选择器

时间:2022-09-18 13:36:37浏览次数:96  
标签:return String final uri 选择器 cursor 自带 null Android

工具类:


public class UriTofilePath {
    public static String getFilePathByUri(Context context, Uri uri) {
        String path = null;
        // 4.4及之后的 是以 content:// 开头的,比如 content://com.android.providers.media.documents/document/image%3A235700
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (DocumentsContract.isDocumentUri(context, uri)) {
                if (isExternalStorageDocument(uri)) {
                    // ExternalStorageProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    if ("primary".equalsIgnoreCase(type)) {
                        path = Environment.getExternalStorageDirectory() + "/" + split[1];
                        return path;
                    }
                } else if (isDownloadsDocument(uri)) {
                    // DownloadsProvider
                    final String id = DocumentsContract.getDocumentId(uri);
                    final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                                                                      Long.valueOf(id));
                    path = getDataColumn(context, contentUri, null, null);
                    return path;
                } else if (isMediaDocument(uri)) {
                    // MediaProvider
                    final String docId = DocumentsContract.getDocumentId(uri);
                    final String[] split = docId.split(":");
                    final String type = split[0];
                    Uri contentUri = null;
                    if ("image".equals(type)) {
                        contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    } else if ("video".equals(type)) {
                        contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                    } else if ("audio".equals(type)) {
                        contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                    }
                    final String selection = "_id=?";
                    final String[] selectionArgs = new String[]{split[1]};
                    path = getDataColumn(context, contentUri, selection, selectionArgs);
                    return path;
                }
            }
        }else {
            // 以 file:// 开头的
            if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
                path = uri.getPath();
                return path;
            }
            // 以 content:// 开头的,比如 content://media/extenral/images/media/17766
            if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
                if (cursor != null) {
                    if (cursor.moveToFirst()) {
                        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                        if (columnIndex > -1) {
                            path = cursor.getString(columnIndex);
                        }
                    }
                    cursor.close();
                }
                return path;
            }
        }
        return null;
    }
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
    private static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}


Activity内代码:


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
    intent1.addCategory(Intent.CATEGORY_OPENABLE);
    intent1.setType("*/*");
    

    Intent chooser = new Intent(Intent.ACTION_CHOOSER);
    chooser.putExtra(Intent.EXTRA_TITLE, "File Chooser");
    chooser.putExtra(Intent.EXTRA_INTENT, intent1);
    startActivityForResult(chooser, 1);
    
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        
        Uri result = data.getData();
        
        Toast.makeText(this,new UriTofilePath().getFilePathByUri(this,result),Toast.LENGTH_SHORT).show();
        }
        
        return;
    }

标签:return,String,final,uri,选择器,cursor,自带,null,Android
From: https://www.cnblogs.com/hazjblog/p/adusesysfileseler.html

相关文章

  • 层次选择器
    层次选择器后代选择器简介后代选择器可以选择作为某元素后代的元素(包括儿子,孙子,重孙子)两个元素之间的层次间隔可以是无限的示例<!DOCTYPEhtml><htmllang="e......
  • 【Scan Kit】集成扫码服务时Android Studio总是报错OOM如何解决?
    ​【问题描述】1、项目中已经集成了华为推送服务,现在还需要集成华为的统一扫码服务,然后就在appmodule的build.gradle文件中添加了如下的依赖:implementation'com.huaw......
  • Android安卓浏览器视频层级永远顶层问题解决方案
    在安卓手机上,使用video播放视频有个问题,video控件层级会永远在顶层,不利于视频互动H5开发,而IOS手机上不会有此问题。腾讯给出了如下解决方案:<videosrc="http://xxx.mp4......
  • 12.2常见的标签选择器
    #8种定位方式#importtimefromtimeimportsleepfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydriver=webdriver.Chrome()#1.id定位#2......
  • JDK 自带的服务发现框架 ServiceLoader 好用吗?
    请点赞关注,你的支持对我意义重大。......
  • 【css3】选择器 :nth-of-type(n)和:nth-child(n) 的区别
          参考:https://blog.csdn.net/dangbai01_/article/details/88545350?spm=1001.2101.3001.6650.3&utm_medium=distribute.pc_relevant.none-task-blog-2%7E......
  • uni-app Android真机调试
    uni-app设置安卓手机真机调试和手机连接之后,还是不能真机调试,如下图   现在开始进行设置,安卓手机第一步:电脑与手机用数据线连接起来,会弹出如下图,   点击......
  • 逆向 | frida android hook 入门总结
    逆向|fridaandroidhook入门总结最近在备课,整理到这一块儿了,顺带就把以前的东西整理一下。比较好的参考文章:https://www.jianshu.com/p/0fa6138fafc9#hook重载函......
  • Selenium选择器学习
    Selenium选择器推荐用CSS选择器 Ifyoudon’tcareabouttheorderingofchildelements,youcanuseanattributeselectorinseleniumtochooseelementsbase......
  • Mac 下反编译Android APK
    准备工作:安装ApkTool、dex2jar、JD-GUI安装ApkTool1、下载ApkTool。大家可以从 https://ibotpeaches.github.io/Apktool/install/ 上下载ApkTool2、安装ApkTool(1)将......