android Q 使用 ACTION_OPEN_DOCUMENT_TREE 选择目录进行遍历文件夹下文件

android Q 使用 ACTION_OPEN_DOCUMENT_TREE 选择目录进行遍历文件夹下文件

  • 前期准备-图片选择
    • 获取
      我们都知道如何获取图片使用,使用如下代码即可打开一个系统的图片选择器
      	val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
      	intent.addCategory(Intent.CATEGORY_OPENABLE)
      	intent.type = "image/*"
      	startActivityForResult(intent, PICK_PIC_REQUEST_CODE)
      
      然后在onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)方法中使用val uri=data?.data获取到图片到uri
    • 读取
      拿到图片uri后通过以下代码转化为bitmap对象(请注意如果选取到uri不是应用自身创建到文件,是需要读写权限的),拿到bitmap以后你就可以为所欲为了
      //通过流转化成bitmap对象
        val inputStream: InputStream? = contentResolver.openInputStream(uri)
        val bitmap= BitmapFactory.decodeStream(inputStream)
      
  • 如何获取文件夹
    • 选择文件夹
      我们知道了如何选择文件,那么选择文件夹呢?查找api可以发现android 为我们提供一个 Intent.ACTION_OPEN_DOCUMENT_TREE字面意思就知道是选择文件夹的,直接上代码

       val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
       startActivityForResult(intent, PICK_DIR_REQUEST_CODE)
      
    • 获取文件夹uri
      同文件获取一样,在onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)方法中使用val uri=data?.data获取到文件夹uri,他可能长这样

         content://com.android.providers.downloads.documents/tree/downloads
      
    • 读文件夹下内容
      拿到文件夹的uri后就要进行遍历了,这时需要了解另一个类 DocumentFile,下面一起看如何根据uri获取文件夹下的文件,如有疑问请看注释

      	//获取onActivityResult中获取文件夹uri
      	 val uri = data?.data      
      	 val listUri = mutableListOf<Uri>()        
      	 uri?.let { 
       		//content://com.android.providers.downloads.documents/tree/downloads
        	  //基于文件夹uri构造DocumentFile,
      		val documentFile = DocumentFile.fromTreeUri(this, it)
      		//拿到文件夹下文件列表
      		val list= documentFile?.listFiles()
      		//遍历
      		list?.forEach {
      				  //文件名
                	    it.name
                 	   //文件类型
                 	   it.type
                 	   //获取文件夹下的图片,并将图片uri保存
                  	  if (it.isFile&&it.canRead()&& MimeType.isImage(it.type))   {
                     	     listUri.add(it.uri)
                         	 println("${it.uri} ${it.name} ${it.type} " )
                       	  }
                 	   }
            	 }
      	```
      * 拿到文件夹下uri列表以后怎么操作,都很容易了.
      

最后提供一个常用的文件类型判断类

 enum class MimeType(val value: String) {
    _png("image/png"),
    _jpeg("image/jpeg"),
    _jpg("image/jpeg"),
    _webp("image/webp"),
    _gif("image/gif"),
    _bmp("image/bmp"),
    _3gp("video/3gpp"),
    _apk("application/vnd.android.package-archive"),
    _asf("video/x-ms-asf"),
    _avi("video/x-msvideo"),
    _bin("application/octet-stream"),
    _c("text/plain"),
    _class("application/octet-stream"),
    _conf("text/plain"),
    _cpp("text/plain"),
    _doc("application/msword"),
    _docx("application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
    _xls("application/vnd.ms-excel"),
    _xlsx("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
    _exe("application/octet-stream"),
    _gtar("application/x-gtar"),
    _gz("application/x-gzip"),
    _h("text/plain"),
    _htm("text/html"),
    _html("text/html"),
    _jar("application/java-archive"),
    _java("text/plain"),
    _js("application/x-javascript"),
    _log("text/plain"),
    _m3u("audio/x-mpegurl"),
    _m4a("audio/mp4a-latm"),
    _m4b("audio/mp4a-latm"),
    _m4p("audio/mp4a-latm"),
    _m4u("video/vnd.mpegurl"),
    _m4v("video/x-m4v"),
    _mov("video/quicktime"),
    _mp2("audio/x-mpeg"),
    _mp3("audio/x-mpeg"),
    _mp4("video/mp4"),
    _mpc("application/vnd.mpohun.certificate"),
    _mpe("video/mpeg"),
    _mpeg("video/mpeg"),
    _mpg("video/mpeg"),
    _mpg4("video/mp4"),
    _mpga("audio/mpeg"),
    _msg("application/vnd.ms-outlook"),
    _ogg("audio/ogg"),
    _pdf("application/pdf"),
    _pps("application/vnd.ms-powerpoint"),
    _ppt("application/vnd.ms-powerpoint"),
    _pptx("application/vnd.openxmlformats-officedocument.presentationml.presentation"),
    _prop("text/plain"),
    _rc("text/plain"),
    _rmvb("audio/x-pn-realaudio"),
    _rtf("application/rtf"),
    _sh("text/plain"),
    _tar("application/x-tar"),
    _tgz("application/x-compressed"),
    _txt("text/plain"),
    _wav("audio/x-wav"),
    _wma("audio/x-ms-wma"),
    _wmv("audio/x-ms-wmv"),
    _wps("application/vnd.ms-works"),
    _xml("text/plain"),
    _z("application/x-compress"),
    _zip("application/x-zip-compressed"),
    _0("*/*"),
    ;

    companion object {
        fun isImage(mimeType: String?): Boolean {
            return mimeType?.let {
                _webp.value == mimeType ||
                        _png.value == mimeType ||
                        _jpeg.value == mimeType ||
                        _jpg.value == mimeType ||
                        _bmp.value == mimeType ||
                        _gif.value == mimeType
            } ?: false
        }

        fun isGif(mimeType: String?): Boolean {
            return mimeType?.let {
                _gif.value == mimeType
            } ?: false
        }

        fun isApk(mimeType: String?) = mimeType?.let {
            _apk.value == mimeType
        } ?: false

        fun isVideo(mimeType: String?) = mimeType?.let {
            _m3u.value == mimeType || _avi.value == mimeType
        } ?: false
    }
}

你可能感兴趣的:(Android,开发)