├── app
├── .gitignore
├── src
│ ├── main
│ │ ├── assets
│ │ │ ├── test4.txt
│ │ │ ├── test1.png
│ │ │ ├── test2.jpg
│ │ │ └── test3.pdf
│ │ ├── res
│ │ │ ├── values
│ │ │ │ ├── strings.xml
│ │ │ │ ├── colors.xml
│ │ │ │ └── themes.xml
│ │ │ ├── mipmap-hdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ │ ├── ic_launcher.png
│ │ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-anydpi-v26
│ │ │ │ ├── ic_launcher.xml
│ │ │ │ └── ic_launcher_round.xml
│ │ │ ├── values-night
│ │ │ │ └── themes.xml
│ │ │ ├── xml
│ │ │ │ └── filepaths.xml
│ │ │ ├── drawable-v24
│ │ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── layout
│ │ │ │ └── activity_main.xml
│ │ │ └── drawable
│ │ │ │ └── ic_launcher_background.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── alexlu
│ │ │ │ └── androidstorage
│ │ │ │ ├── App.kt
│ │ │ │ ├── bean
│ │ │ │ └── MediaStoreImage.kt
│ │ │ │ ├── file
│ │ │ │ ├── PDFUtils.kt
│ │ │ │ ├── FileSizeUtil.java
│ │ │ │ ├── PicturesUtil.kt
│ │ │ │ └── FilePath.kt
│ │ │ │ ├── util
│ │ │ │ ├── MediaStoreUtil.kt
│ │ │ │ └── BitmapUtil.kt
│ │ │ │ └── MainActivity.kt
│ │ └── AndroidManifest.xml
│ ├── test
│ │ └── java
│ │ │ └── com
│ │ │ └── alexlu
│ │ │ └── androidstorage
│ │ │ └── ExampleUnitTest.kt
│ └── androidTest
│ │ └── java
│ │ └── com
│ │ └── alexlu
│ │ └── androidstorage
│ │ └── ExampleInstrumentedTest.kt
├── proguard-rules.pro
└── build.gradle
├── settings.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── vcs.xml
├── misc.xml
├── gradle.xml
└── jarRepositories.xml
├── .gitattributes
├── image
└── test.jpg
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── .gitignore
├── gradle.properties
├── gradlew.bat
├── gradlew
└── README.md
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/app/src/main/assets/test4.txt:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | rootProject.name = "AndroidStorageDemo"
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/image/test.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/image/test.jpg
--------------------------------------------------------------------------------
/app/src/main/assets/test1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/assets/test1.png
--------------------------------------------------------------------------------
/app/src/main/assets/test2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/assets/test2.jpg
--------------------------------------------------------------------------------
/app/src/main/assets/test3.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/assets/test3.pdf
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidStorageDemo
3 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/xluu233/AndroidStorageDemo/HEAD/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Fri Mar 19 14:11:07 CST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/App.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage
2 |
3 | import android.app.Application
4 |
5 | class App : Application() {
6 |
7 | companion object{
8 | lateinit var instance:Application
9 | }
10 |
11 | override fun onCreate() {
12 | super.onCreate()
13 | instance = this
14 | }
15 |
16 |
17 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 |
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/bean/MediaStoreImage.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.bean
2 |
3 | import android.net.Uri
4 | import java.util.*
5 |
6 | /**
7 | * @ClassName MediaStoreImage
8 | * @Description TODO
9 | * @Author AlexLu_1406496344@qq.com
10 | * @Date 2021/7/23 9:45
11 | */
12 | data class MediaStoreImage(
13 | val id: Long,
14 | val name: String,
15 | val time:String?,
16 | val contentUri: Uri
17 | )
18 |
--------------------------------------------------------------------------------
/app/src/test/java/com/alexlu/androidstorage/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/alexlu/androidstorage/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.alexlu.androidstorage", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
20 |
21 |
--------------------------------------------------------------------------------
/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
16 |
--------------------------------------------------------------------------------
/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/filepaths.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
8 |
9 |
10 |
13 |
14 |
15 |
18 |
19 |
20 |
23 |
24 |
25 |
28 |
29 |
30 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 |
7 |
8 |
9 |
10 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
33 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | id 'kotlin-android-extensions'
5 | id 'kotlin-kapt'
6 | }
7 |
8 | android {
9 | compileSdkVersion 30
10 | buildToolsVersion "30.0.3"
11 |
12 | defaultConfig {
13 | applicationId "com.alexlu.androidstorage"
14 | minSdkVersion 21
15 | targetSdkVersion 30
16 | versionCode 1
17 | versionName "1.0"
18 |
19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
20 | }
21 |
22 | buildTypes {
23 | release {
24 | minifyEnabled false
25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
26 | }
27 | }
28 | compileOptions {
29 | sourceCompatibility JavaVersion.VERSION_1_8
30 | targetCompatibility JavaVersion.VERSION_1_8
31 | }
32 | kotlinOptions {
33 | jvmTarget = '1.8'
34 | }
35 | buildFeatures {
36 | dataBinding = true
37 | viewBinding = true
38 | }
39 | }
40 |
41 | dependencies {
42 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
43 | implementation 'androidx.core:core-ktx:1.3.2'
44 | implementation 'androidx.appcompat:appcompat:1.2.0'
45 | implementation 'com.google.android.material:material:1.3.0'
46 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
47 | testImplementation 'junit:junit:4.+'
48 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
49 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
50 |
51 | //Rxpermissions https://github.com/tbruyelle/RxPermissions
52 | implementation 'com.github.tbruyelle:rxpermissions:0.12'
53 |
54 |
55 | // Glide
56 | implementation 'com.github.bumptech.glide:glide:4.11.0'
57 | kapt 'com.github.bumptech.glide:compiler:4.11.0'
58 |
59 | //rxjava
60 | implementation 'io.reactivex.rxjava3:rxjava:3.0.10'
61 | implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
62 |
63 |
64 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/file/PDFUtils.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.file
2 |
3 | import android.graphics.Bitmap
4 | import android.graphics.Matrix
5 | import android.graphics.Paint
6 | import android.graphics.pdf.PdfDocument
7 | import android.print.PrintAttributes
8 | import com.alexlu.androidstorage.util.FilePath
9 | import java.io.*
10 |
11 | /**
12 | * @ClassName PdfUtils
13 | * @Description
14 | * @Author AlexLu_1406496344@qq.com
15 | * @Date 2021/3/19 17:33
16 | */
17 | object PDFUtils {
18 |
19 | const val StorageName = ""
20 |
21 | /**
22 | * 将Bitmap保存为PDF文件在Download目录下
23 | *
24 | * @param bitmaps
25 | * @param fileName 文件名
26 | */
27 | fun saveBitmapForPdf(bitmaps: ArrayList, fileName: String): File {
28 | val doc = PdfDocument()
29 | val pageWidth: Int = PrintAttributes.MediaSize.ISO_A4.widthMils * 72 / 1000
30 | val scale = pageWidth.toFloat() / bitmaps[0].width.toFloat()
31 | val pageHeight = (bitmaps[0].height * scale).toInt()
32 | val matrix = Matrix()
33 | matrix.postScale(scale, scale)
34 | val paint = Paint(Paint.ANTI_ALIAS_FLAG)
35 |
36 | for (i in 0 until bitmaps.size) {
37 | val newPage = PdfDocument.PageInfo.Builder(pageWidth, pageHeight, i).create()
38 | val page = doc.startPage(newPage)
39 | val canvas = page.canvas
40 | canvas.drawBitmap(bitmaps[i], matrix, paint)
41 | doc.finishPage(page)
42 | }
43 |
44 | val file = File(FilePath.getExternalDownloadPath(StorageName), fileName)
45 | var outputStream: FileOutputStream? = null
46 | try {
47 | outputStream = FileOutputStream(file)
48 | doc.writeTo(outputStream)
49 | } catch (e: FileNotFoundException) {
50 | e.printStackTrace()
51 | } catch (e: IOException) {
52 | e.printStackTrace()
53 | } finally {
54 | doc.close()
55 | try {
56 | outputStream?.close()
57 | } catch (e: IOException) {
58 | e.printStackTrace()
59 | }
60 | }
61 | return file
62 | }
63 |
64 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/util/MediaStoreUtil.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.util
2 |
3 | import android.content.ContentUris
4 | import android.content.Context
5 | import android.database.Cursor
6 | import android.net.Uri
7 | import android.provider.MediaStore
8 |
9 |
10 | /**
11 | * @ClassName MediaStoreUtil
12 | * @Description TODO
13 | * @Author AlexLu_1406496344@qq.com
14 | * @Date 2021/7/23 9:52
15 | */
16 | object MediaStoreUtil {
17 |
18 | /**
19 | * TODO 查询相册图片
20 | *
21 | * @param context
22 | */
23 | fun getAlbumList(context: Context):List{
24 | val list= mutableListOf()
25 | val cursor = context.contentResolver.query(
26 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
27 | null,
28 | null,
29 | null,
30 | "${MediaStore.MediaColumns.DATE_ADDED} desc"
31 | )
32 | if (cursor != null) {
33 | while (cursor.moveToNext()) {
34 | val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
35 | val uri = ContentUris.withAppendedId(
36 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
37 | id
38 | )
39 | list += uri
40 | }
41 | cursor.close()
42 | }
43 | return list
44 | }
45 |
46 |
47 | fun getVideoList(context: Context){
48 | val project = arrayOf(
49 | MediaStore.Video.Media._ID,
50 | MediaStore.Video.Media.BUCKET_DISPLAY_NAME,
51 | MediaStore.Video.Media.DURATION, //视频的时长
52 | MediaStore.Video.Media.DATE_MODIFIED
53 | )
54 |
55 | val cursor: Cursor ?= context.contentResolver.query(
56 | MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
57 | project,
58 | MediaStore.Video.Media.MIME_TYPE + "=?",
59 | arrayOf("video/mp4"), //这里只查了mp4格式
60 | MediaStore.Video.Media.DATE_MODIFIED + " desc"
61 | )
62 | if (cursor != null) {
63 | while (cursor.moveToNext()) {
64 | val id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID))
65 | val uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
66 | println("image uri is $uri")
67 | }
68 | cursor.close()
69 | }
70 | }
71 |
72 |
73 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
10 |
22 |
23 |
34 |
35 |
44 |
45 |
54 |
55 |
64 |
65 |
66 |
75 |
76 |
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/file/FileSizeUtil.java:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.file;
2 |
3 | import android.util.Log;
4 |
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.text.DecimalFormat;
8 |
9 | /**
10 | * @CreateBy HaiyuKing
11 | * @Used android 获取文件夹或文件的大小 以B、KB、MB、GB 为单位
12 | * @参考资料 http://blog.csdn.net/jiaruihua_blog/article/details/13622939
13 | */
14 | public class FileSizeUtil {
15 |
16 | public static final int SIZETYPE_B = 1;//获取文件大小单位为B的double值
17 | public static final int SIZETYPE_KB = 2;//获取文件大小单位为KB的double值
18 | public static final int SIZETYPE_MB = 3;//获取文件大小单位为MB的double值
19 | public static final int SIZETYPE_GB = 4;//获取文件大小单位为GB的double值
20 | /**
21 | * 获取指定文件或指定文件夹的的指定单位的大小
22 | * @param filePath 文件路径
23 | * @param sizeType 获取大小的类型1为B、2为KB、3为MB、4为GB
24 | * @return double值的大小
25 | */
26 | public static double getFolderOrFileSize(String filePath,int sizeType){
27 | File file=new File(filePath);
28 | long blockSize=0;
29 | try {
30 | if(file.isDirectory()){
31 | blockSize = getFolderSize(file);
32 | }else{
33 | blockSize = getFileSize(file);
34 | }
35 | } catch (Exception e) {
36 | e.printStackTrace();
37 | Log.e("获取文件大小","获取失败!");
38 | }
39 | return FormetFileSize(blockSize, sizeType);
40 | }
41 | /**
42 | * 调用此方法自动计算指定文件或指定文件夹的大小
43 | * @param filePath 文件路径
44 | * @return 计算好的带B、KB、MB、GB的字符串
45 | */
46 | public static String getAutoFolderOrFileSize(String filePath){
47 | File file=new File(filePath);
48 | long blockSize=0;
49 | try {
50 | if(file.isDirectory()){
51 | blockSize = getFolderSize(file);
52 | }else{
53 | blockSize = getFileSize(file);
54 | }
55 | } catch (Exception e) {
56 | e.printStackTrace();
57 | Log.e("获取文件大小","获取失败!");
58 | }
59 | return FormetFileSize(blockSize);
60 | }
61 | /**
62 | * 获取指定文件的大小
63 | * @param file
64 | * @return
65 | * @throws Exception
66 | */
67 | private static long getFileSize(File file) throws Exception
68 | {
69 | long size = 0;
70 | if (file.exists()){
71 | FileInputStream fis = null;
72 | fis = new FileInputStream(file);
73 | size = fis.available();
74 | fis.close();
75 | }
76 | else{
77 | file.createNewFile();
78 | Log.e("获取文件大小","文件不存在!");
79 | }
80 |
81 | return size;
82 | }
83 |
84 | /**
85 | * 获取指定文件夹的大小
86 | * @param file
87 | * @return
88 | * @throws Exception
89 | */
90 | private static long getFolderSize(File file) throws Exception
91 | {
92 | long size = 0;
93 | File flist[] = file.listFiles();
94 | for (int i = 0; i < flist.length; i++){
95 | if (flist[i].isDirectory()){
96 | size = size + getFolderSize(flist[i]);
97 | }
98 | else{
99 | size =size + getFileSize(flist[i]);
100 | }
101 | }
102 | return size;
103 | }
104 | /**
105 | * 转换文件大小
106 | * @param fileSize
107 | * @return
108 | */
109 | private static String FormetFileSize(long fileSize)
110 | {
111 | DecimalFormat df = new DecimalFormat("#.00");
112 | String fileSizeString = "";
113 | String wrongSize="0B";
114 | if(fileSize==0){
115 | return wrongSize;
116 | }
117 | if (fileSize < 1024){
118 | fileSizeString = df.format((double) fileSize) + "B";
119 | }
120 | else if (fileSize < 1048576){
121 | fileSizeString = df.format((double) fileSize / 1024) + "KB";
122 | }
123 | else if (fileSize < 1073741824){
124 | fileSizeString = df.format((double) fileSize / 1048576) + "MB";
125 | }
126 | else{
127 | fileSizeString = df.format((double) fileSize / 1073741824) + "GB";
128 | }
129 | return fileSizeString;
130 | }
131 | /**
132 | * 转换文件大小,指定转换的类型
133 | * @param fileSize
134 | * @param sizeType
135 | * @return
136 | */
137 | private static double FormetFileSize(long fileSize,int sizeType)
138 | {
139 | DecimalFormat df = new DecimalFormat("#.00");
140 | double fileSizeLong = 0;
141 | switch (sizeType) {
142 | case SIZETYPE_B:
143 | fileSizeLong=Double.valueOf(df.format((double) fileSize));
144 | break;
145 | case SIZETYPE_KB:
146 | fileSizeLong=Double.valueOf(df.format((double) fileSize / 1024));
147 | break;
148 | case SIZETYPE_MB:
149 | fileSizeLong=Double.valueOf(df.format((double) fileSize / 1048576));
150 | break;
151 | case SIZETYPE_GB:
152 | fileSizeLong=Double.valueOf(df.format((double) fileSize / 1073741824));
153 | break;
154 | default:
155 | break;
156 | }
157 | return fileSizeLong;
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/file/PicturesUtil.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.file
2 |
3 | import android.content.ContentResolver
4 | import android.content.ContentValues
5 | import android.content.Context
6 | import android.graphics.Bitmap
7 | import android.os.Build
8 | import android.os.Environment
9 | import android.provider.MediaStore
10 | import androidx.annotation.RequiresApi
11 | import com.alexlu.androidstorage.util.BitmapUtil
12 | import java.io.*
13 |
14 |
15 | /**
16 | * 图片操作工具类
17 | */
18 | object PicturesUtil {
19 |
20 | const val pic_save_path = "ABC啦啦啦"
21 |
22 |
23 | /**
24 | * TODO Bitmap保存为图片
25 | * @param context
26 | * @param bitmap 输入源
27 | * @param file 输出文件
28 | * @param refreshAlbum 是否刷新相册,刷新将会复制源文件到 SDcard->Pitures 目录并删除源文件
29 | */
30 | fun saveBitmap2File(context: Context?=null, bitmap: Bitmap?, file: File, refreshAlbum:Boolean = false) {
31 | try {
32 | val fos = FileOutputStream(file)
33 | bitmap?.compress(Bitmap.CompressFormat.JPEG, 100, fos)
34 | fos.flush()
35 | fos.close()
36 | } catch (e: FileNotFoundException) {
37 | e.printStackTrace()
38 | } catch (e: IOException) {
39 | e.printStackTrace()
40 | } finally {
41 | if (refreshAlbum) context?.let {
42 | refreshSystemAlbum(it,file)
43 | }
44 | }
45 | }
46 |
47 | /**
48 | * TODO 网络url保存为图片
49 | */
50 | fun saveUrl2File(url:String?,file: File){
51 | val bitmap = BitmapUtil.getUrlBitmap(url)
52 | saveBitmap2File(bitmap = bitmap,file = file)
53 | }
54 |
55 | /**
56 | * TODO 通知系统相册更新
57 | */
58 | private fun refreshSystemAlbum(context: Context, file: File) {
59 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
60 | insertPicInAndroidQ(context, file,deleteSource = true)
61 | } else {
62 | //通知系统图库更新
63 | val value = ContentValues()
64 | value.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
65 | value.put(MediaStore.Images.Media.DATA, file.absolutePath)
66 | context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, value)
67 | }
68 | }
69 |
70 | /**
71 | * TODO 复制文件
72 | * @param source 输入文件
73 | * @param target 输出文件
74 | */
75 | fun copyFile(source: File?, target: File?) {
76 | var fileInputStream: FileInputStream? = null
77 | var fileOutputStream: FileOutputStream? = null
78 | try {
79 | fileInputStream = FileInputStream(source)
80 | fileOutputStream = FileOutputStream(target)
81 | val buffer = ByteArray(1024)
82 | while (fileInputStream.read(buffer) > 0) {
83 | fileOutputStream.write(buffer)
84 | }
85 | } catch (e: Exception) {
86 | e.printStackTrace()
87 | } finally {
88 | try {
89 | source?.delete()
90 | fileInputStream?.close()
91 | fileOutputStream?.close()
92 | } catch (e: IOException) {
93 | e.printStackTrace()
94 | }
95 | }
96 | }
97 |
98 | /**
99 | * TODO Android Q以后向系统相册插入图片
100 | * 注意:这种方式将会复制源文件到 Picture/SAVE_PATH 目录下,可以选择在插入之后删除源文件
101 | * @param deleteSource 是否删除源文件
102 | */
103 | @RequiresApi(Build.VERSION_CODES.Q)
104 | private fun insertPicInAndroidQ(context: Context, file: File, deleteSource:Boolean) {
105 | val values = ContentValues()
106 | values.put(MediaStore.Images.Media.DESCRIPTION, file.name)
107 | values.put(MediaStore.Images.Media.DISPLAY_NAME, file.name)
108 | values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
109 | values.put(MediaStore.Images.Media.TITLE, "Image.jpg")
110 | values.put(MediaStore.Images.Media.RELATIVE_PATH, getMediaStorePath())
111 | //"Pictures/${pic_save_path}/"
112 |
113 | val external = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
114 | val resolver: ContentResolver = context.contentResolver
115 | val insertUri = resolver.insert(external, values)
116 | val inputStream: BufferedInputStream?
117 | var os: OutputStream? = null
118 | try {
119 | inputStream = BufferedInputStream(FileInputStream(file))
120 | if (insertUri != null) {
121 | os = resolver.openOutputStream(insertUri)
122 | }
123 | if (os != null) {
124 | val buffer = ByteArray(1024 * 4)
125 | var len: Int
126 | while (inputStream.read(buffer).also { len = it } != -1) {
127 | os.write(buffer, 0, len)
128 | }
129 | os.flush()
130 | }
131 | } catch (e: IOException) {
132 | e.printStackTrace()
133 | } finally {
134 | os?.close()
135 | if (deleteSource) file.delete()
136 | }
137 | }
138 |
139 | private fun getMediaStorePath(): String {
140 | return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
141 | // full path
142 | "${Environment.getExternalStorageDirectory().absolutePath}/" + "${Environment.DIRECTORY_PICTURES}/$pic_save_path/"
143 | } else {
144 | // relative path
145 | "${Environment.DIRECTORY_PICTURES}/$pic_save_path/"
146 | }
147 | }
148 |
149 | }
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/util/BitmapUtil.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.util
2 |
3 | import android.content.Context
4 | import android.graphics.*
5 | import android.media.ExifInterface
6 | import android.net.Uri
7 | import android.provider.MediaStore
8 | import java.io.*
9 | import java.net.HttpURLConnection
10 | import java.net.URL
11 | import java.net.URLConnection
12 | import java.nio.ByteBuffer
13 |
14 |
15 | /**
16 | * @ClassName BitmapUtil
17 | * @Description Bitmap操作工具类
18 | * @Author AlexLu_1406496344@qq.com
19 | * @Date 2021/7/13 15:29
20 | */
21 | object BitmapUtil {
22 |
23 | // BitmapFactory会导致图像旋转
24 | // 先记录旋转角度,在转为bitmap之后再旋转回来
25 |
26 | /**
27 | * TODO file转bitmap
28 | */
29 | fun convertToBitmap(file: File?): Bitmap? {
30 | if (file==null) return null
31 | val rotate = getRotateDegree(file.absolutePath)
32 | val bitmap = BitmapFactory.decodeFile(file.absolutePath)
33 | return rotateBitmap(bitmap, rotate)
34 | }
35 |
36 | /**
37 | * TODO filePath转bitmap
38 | */
39 | fun convertToBitmap(path: String?): Bitmap? {
40 | val rotate = getRotateDegree(path)
41 | val bitmap = BitmapFactory.decodeFile(path)
42 | return rotateBitmap(bitmap, rotate)
43 | }
44 |
45 | /**
46 | * TODO Uri转Bitmap
47 | */
48 | fun convertToBitmap(uri: Uri?, context: Context): Bitmap? {
49 | if (uri==null) return null
50 | val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: return null
51 | val bitmap = BitmapFactory.decodeFileDescriptor(fd.fileDescriptor)
52 | fd.close()
53 | //val bitmap = MediaStore.Images.Media.getBitmap(context.contentResolver, uri)
54 | return bitmap
55 | }
56 |
57 | /**
58 | * TODO Assert资源文件转Bitmap
59 | */
60 | fun assert2Bitmap(fileName: String, context: Context) : Bitmap?{
61 | var ins: InputStream? = null
62 | try {
63 | ins = context.resources.assets.open(fileName)
64 | } catch (e: IOException) {
65 | e.printStackTrace()
66 | }
67 | return BitmapFactory.decodeStream(ins)
68 | }
69 |
70 | /**
71 | * TODO 获取图片的旋转角度
72 | * 只能通过原始文件获取,如果已经进行过bitmap操作无法获取。
73 | */
74 | private fun getRotateDegree(path: String?): Float {
75 | var result = 0f
76 | if (path.isNullOrEmpty()) return result
77 |
78 | try {
79 | val exif = ExifInterface(path)
80 | val orientation = exif.getAttributeInt(
81 | ExifInterface.TAG_ORIENTATION,
82 | ExifInterface.ORIENTATION_NORMAL
83 | )
84 | when (orientation) {
85 | ExifInterface.ORIENTATION_ROTATE_90 -> result = 90f
86 | ExifInterface.ORIENTATION_ROTATE_180 -> result = 180f
87 | ExifInterface.ORIENTATION_ROTATE_270 -> result = 270f
88 | }
89 | } catch (ignore: IOException) {
90 | return result
91 | }
92 | return result
93 | }
94 |
95 | /**
96 | * TODO 处理图片旋转
97 | */
98 | private fun rotateBitmap(bitmap: Bitmap?, rotate: Float): Bitmap? {
99 | if (bitmap == null) return null
100 | if (rotate==0f) return bitmap
101 |
102 | val w = bitmap.width
103 | val h = bitmap.height
104 |
105 | // Setting post rotate to 90
106 | val mtx = Matrix()
107 | mtx.postRotate(rotate)
108 |
109 | val outBit = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true)
110 | bitmap.recycle()
111 | return outBit
112 | }
113 |
114 | /**
115 | * TODO Bitmap压缩
116 | * @param quality 0-100
117 | */
118 | fun Bitmap.compressQuality(quality: Int = 90):Bitmap = apply{
119 | val bos = ByteArrayOutputStream()
120 | this.compress(Bitmap.CompressFormat.JPEG, quality, bos)
121 | val bytes = bos.toByteArray()
122 | BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
123 | }
124 |
125 |
126 | /**
127 | * TODO Bitmap转ByteArray
128 | */
129 | fun convertToByteArray(bitmap: Bitmap?):ByteArray? {
130 | if (bitmap==null) return null
131 | val bytes: Int = bitmap.byteCount
132 | val buf: ByteBuffer = ByteBuffer.allocate(bytes)
133 | bitmap.copyPixelsToBuffer(buf)
134 |
135 | return buf.array()
136 | }
137 |
138 | /**
139 | * TODO Bitmap转ByteBuffer
140 | */
141 | fun convertToByteBuffer(bitmap: Bitmap?):ByteBuffer? {
142 | if (bitmap==null) return null
143 | val bytes: Int = bitmap.byteCount
144 | val buf: ByteBuffer = ByteBuffer.allocate(bytes)
145 | bitmap.copyPixelsToBuffer(buf)
146 | return buf
147 | }
148 |
149 | /**
150 | * TODO byteArray转Bitmap
151 | */
152 | fun byte2Bitmap(byteArray: ByteArray?):Bitmap?{
153 | if (byteArray==null) return null
154 | var bitmap : Bitmap ?= null
155 | bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.size);
156 | return bitmap
157 | }
158 |
159 | /**
160 | * 网络url转bitmap
161 | */
162 | fun getUrlBitmap(url: String?): Bitmap? {
163 | var bm: Bitmap? = null
164 | try {
165 | val iconUrl = URL(url)
166 | val conn: URLConnection = iconUrl.openConnection()
167 | val http: HttpURLConnection = conn as HttpURLConnection
168 | val length: Int = http.contentLength
169 | conn.connect()
170 | // 获得图像的字符流
171 | val `is`: InputStream = conn.getInputStream()
172 | val bis = BufferedInputStream(`is`, length)
173 | bm = BitmapFactory.decodeStream(bis)
174 | bis.close()
175 | `is`.close() // 关闭流
176 | } catch (e: Exception) {
177 | e.printStackTrace()
178 | }
179 | return bm
180 | }
181 |
182 | /**
183 | * TODO 最佳缩放Bitmap
184 | */
185 | fun zoomBitmap(bm: Bitmap?, width: Int, height: Int): Bitmap? {
186 | if (bm==null || bm.isRecycled){
187 | return null
188 | }
189 | val srcWidth = bm.width
190 | val srcHeight = bm.height
191 | val widthScale = width * 1.0f / srcWidth
192 | val heightScale = height * 1.0f / srcHeight
193 | val matrix = Matrix()
194 | matrix.postScale(widthScale, heightScale, 0f, 0f)
195 | // 如需要可自行设置 Bitmap.Config.RGB_8888 等等
196 | val bmpRet = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
197 | val canvas = Canvas(bmpRet)
198 | val paint = Paint()
199 | canvas.drawBitmap(bm, matrix, paint)
200 | return bmpRet
201 | }
202 |
203 |
204 | }
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage
2 |
3 | import android.Manifest
4 | import android.graphics.Bitmap
5 | import android.graphics.BitmapFactory
6 | import android.net.Uri
7 | import android.os.Bundle
8 | import android.os.Environment
9 | import android.util.Log
10 | import android.view.View
11 | import androidx.appcompat.app.AppCompatActivity
12 | import androidx.core.content.FileProvider
13 | import com.alexlu.androidstorage.databinding.ActivityMainBinding
14 | import com.alexlu.androidstorage.file.PDFUtils
15 | import com.alexlu.androidstorage.util.FilePath
16 | import com.alexlu.androidstorage.util.MediaStoreUtil
17 | import com.tbruyelle.rxpermissions3.RxPermissions
18 | import com.alexlu.androidstorage.file.PicturesUtil
19 | import java.io.File
20 | import java.io.IOException
21 | import java.io.InputStream
22 |
23 |
24 |
25 | const val TAG = "Android分区存储测试"
26 |
27 |
28 | class MainActivity : AppCompatActivity() {
29 |
30 |
31 | private lateinit var binding: ActivityMainBinding
32 | private lateinit var bitmap:Bitmap
33 |
34 | override fun onCreate(savedInstanceState: Bundle?) {
35 | super.onCreate(savedInstanceState)
36 | binding = ActivityMainBinding.inflate(layoutInflater)
37 | setContentView(binding.root)
38 | RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE).subscribe {
39 | if (it){
40 | Log.d(TAG,"读写权限已获取")
41 | }
42 | }
43 | showPath()
44 | getAsset()
45 | }
46 |
47 | //展示不同api获取到的路径
48 | private fun showPath() {
49 |
50 | Log.d(TAG,Environment.getExternalStorageDirectory().absolutePath)
51 | ///storage/emulated/0
52 |
53 | Log.d(TAG,Environment.getRootDirectory().absolutePath)
54 | ///system
55 |
56 | Log.d(TAG,Environment.getDataDirectory().absolutePath)
57 | ///data
58 |
59 | Log.d(TAG,Environment.getDownloadCacheDirectory().absolutePath)
60 | ///data/cache
61 |
62 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
63 | Log.d(TAG,"getDownloadCacheDirectory():"+Environment.getStorageDirectory().absolutePath)
64 | ///storage
65 | }
66 |
67 | Log.d(TAG,this.filesDir.absolutePath)
68 | ///data/user/0/com.alexlu.androidstorage/files
69 |
70 | Log.d(TAG,this.cacheDir.absolutePath)
71 | ///data/user/0/com.alexlu.androidstorage/cache
72 |
73 | Log.d(TAG,this.codeCacheDir.absolutePath)
74 | ///data/user/0/com.alexlu.androidstorage/code_cache
75 |
76 | Log.d(TAG,"externalCacheDir:"+this.externalCacheDir?.absolutePath)
77 | ///storage/emulated/0/Android/data/com.alexlu.androidstorage/cache
78 |
79 | this.externalMediaDirs.forEach {
80 | Log.d(TAG,"externalMediaDirs:"+it.absolutePath)
81 | ///storage/emulated/0/Android/media/com.alexlu.androidstorage
82 | }
83 |
84 | Log.d(TAG,"getExternalFilesDir:"+this.getExternalFilesDir(null)?.absolutePath)
85 | ///storage/emulated/0/Android/data/com.alexlu.androidstorage/files
86 |
87 |
88 | //预定义的一些常用目录
89 | Log.d(TAG,Environment.DIRECTORY_PICTURES)
90 | //Pictures
91 | Log.d(TAG,Environment.DIRECTORY_DOWNLOADS)
92 | //Download
93 | Log.d(TAG,Environment.DIRECTORY_DCIM)
94 | //DCIM
95 | Log.d(TAG,Environment.DIRECTORY_MUSIC)
96 | //Music
97 | Log.d(TAG,Environment.DIRECTORY_MOVIES)
98 | //Movies
99 | }
100 |
101 | private fun getAsset() {
102 | //这里将一张图片以 AssetFileDescriptor 的形式读取出来
103 | try {
104 | val pic = this.assets.openFd("test1.png")
105 | val `is`: InputStream = pic.createInputStream()
106 | bitmap = BitmapFactory.decodeStream(`is`)
107 | `is`.close()
108 | pic.close()
109 | binding.imageView.setImageBitmap(bitmap)
110 | } catch (e: IOException) {
111 | e.printStackTrace()
112 | }
113 | }
114 |
115 |
116 | /**
117 | * TODO 保存图片到内存存储-私有目录下
118 | */
119 | fun savePic(view: View) {
120 | //创建私有目录cache目录下文件
121 | val file = File(FilePath.getAppCachePath(),"${System.currentTimeMillis()}.jpg")
122 |
123 | //创建私有目录files->image目录下文件
124 | val file2 = File(FilePath.getAppFilePath("image"),"${System.currentTimeMillis()}.jpg")
125 |
126 | PicturesUtil.saveBitmap2File(bitmap = bitmap,file = file)
127 | PicturesUtil.saveBitmap2File(bitmap = bitmap,file = file2)
128 |
129 |
130 | val uri1:Uri = FileProvider.getUriForFile(this,"com.alexlu.androidstorage.fileProvider",file)
131 | Log.d(TAG,"uri1:${uri1}")
132 | //uri1:content://com.alexlu.androidstorage.fileProvider/app_cache/1626865241315.jpg
133 |
134 | val uri2:Uri = Uri.parse(file.absolutePath)
135 | Log.d(TAG,"uri2:${uri2}")
136 | //uri2:/data/user/0/com.alexlu.androidstorage/cache/1626865241315.jpg
137 | }
138 |
139 | /**
140 | * TODO 保存图片到外部存储-公共目录
141 | * 一般图片保存在:sdcard/Pictures
142 | */
143 | fun savePic2(view: View) {
144 | //创建私有目录cache目录下文件
145 | val file = File(FilePath.getExternalPicturesPath("test"),"${System.currentTimeMillis()}.jpg")
146 | PicturesUtil.saveBitmap2File(context = this,bitmap = bitmap,file = file,refreshAlbum = true)
147 | }
148 |
149 | /**
150 | * TODO 保存图片到外部存储-分区目录
151 | */
152 | fun savePic3(view: View) {
153 | ///sdcard/Android/data/com.alexlu.androidstorage/files
154 | val file = File(FilePath.getAppExternalFilePath("这是子目录"),"${System.currentTimeMillis()}.jpg")
155 | PicturesUtil.saveBitmap2File(context = this,bitmap = bitmap,file = file)
156 |
157 | ///sdcard/Android/data/com.alexlu.androidstorage/cache
158 | val file2 = File(FilePath.getAppExternalFilePath(),"${System.currentTimeMillis()}.jpg")
159 | PicturesUtil.saveBitmap2File(context = this,bitmap = bitmap,file = file2)
160 | }
161 |
162 |
163 | /**
164 | * TODO 保存PDF文件
165 | */
166 | fun savePDF(view: View) {
167 | val list = arrayListOf()
168 | list.add(bitmap)
169 | list.add(bitmap)
170 | list.add(bitmap)
171 |
172 | PDFUtils.saveBitmapForPdf(list,"${System.currentTimeMillis()}.pdf")
173 | }
174 |
175 |
176 |
177 | fun testMediaStore(view: View) {
178 | //获取相册图片
179 | /* val result = MediaStoreUtil.getAlbumList(this)
180 | result.forEach {
181 | println("image uri is $it")
182 | }*/
183 |
184 |
185 |
186 | MediaStoreUtil.getVideoList(this)
187 |
188 | }
189 |
190 |
191 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # AndroidStorageDemo
2 | Android文件系统详解
3 |
4 | 总所周知Android上的存储权限一直在更改,从Android增加file provider,到Android10增加分区存储,Google对于存储权限管理越来越严格。我们聊一下Android上的存储Api兼容性适配。
5 |
6 | ## 1. 应用存储空间
7 |
8 | 应用保存数据的方式有如下:
9 | - 文件和媒体数据可以保存在“应用专属存储空间”和“公共存储空间之中”
10 | - 短数据或者偏好设置可以通过sharePreference保存
11 | - 数据库
12 |
13 |
14 | #### 外部存储
15 | 以前的手机是存在SDcard的,但目前很多手机都取消了SDcard,Android上引入了映射机制来创建虚拟的SDcard,我们通过文件管理器看到的路径`storage/emulated/0`就是虚拟SDcard,也就是我们俗称的“外部存储空间”或者“公共存储空间”
16 |
17 | > app申请的读写权限请求都是申请的外部存储空间权限
18 |
19 | #### 内部存储
20 |
21 | 内存存储也就是本app的专享目录,其他app是无法访问的,适合存储敏感文件。
22 | 通过系统api访问到的路径:`/data/user/0/app_packageName/...`
23 | 对应的真是目录:`/data/date/app_packageName/...`
24 |
25 | #### 分区存储
26 | 分区存储实际上就是外部存储空间中建一个app对应目录,本app无须申请权限就可以访问,如果申请读写权限,意味着申请外部空间所有访问权限,**所以分区存储目录是有可能被其他app访问到的。** [官网](https://developer.android.com/training/data-storage?hl=zh-cn#scoped-storage)对它的介绍
27 |
28 | ## 2.权限变更记录
29 |
30 | #### Android6.0引入动态权限
31 |
32 | 申请读写权限需要在Manifest.xml中申明:
33 |
34 | ```
35 |
36 |
37 | ```
38 | Android6.0之前只需申明就可以进行文件读写,Android6.0之后需要进行动态权限申请,也就是要用户同意了才行。权限申请回调很烦人,可以去Github上看一下RxPermission,EasyPermission之类的库。
39 |
40 |
41 | #### Android7.0权限变更
42 |
43 | 自从Android7.0开始之后,禁止使用 `file://`这类型的URI,尝试直接使用这种URI会触发` FileUriExposedException`,建议使用[FileProvider](https://developer.android.com/reference/androidx/core/content/FileProvider?hl=en)来创建`content://`这类型URI
44 |
45 | #### Android10尝试引入分区存储
46 |
47 | 上面已经讲述了分区存储其实就是外部存储空间的app目录,本app无须权限就可以访问。
48 | 在Android10上可以禁用:`android:requestLegacyExternalStorage="true"`,但是在Android11上就不管用了哦,系统会自动忽略啊哈哈
49 |
50 |
51 | > Google首次尝试引入分区存储,我当时听了人都傻了=.= 真能折腾啊
52 |
53 | ## 3. 使用FileProvider
54 |
55 | #### Setup1:
56 |
57 | 在res目录下新建xml目录,在xml目录下新建filepaths.xml文件
58 |
59 |
60 | ```
61 |
62 |
63 |
64 |
65 |
68 |
69 |
70 |
73 |
74 |
75 |
78 |
79 |
80 |
83 |
84 |
85 |
88 |
89 |
90 |
93 |
94 |
95 |
96 | ```
97 |
98 | #### Setup2:
99 |
100 | 在AndroidManifest.xml中申明:
101 |
102 |
103 | ```
104 |
112 |
113 |
119 |
122 |
123 |
124 |
125 |
126 |
127 | ```
128 | 注意这里的`android:authorities="com.alexlu.androidstorage.fileProvider"`修改为自己的包名,
129 |
130 | #### Setup3:
131 |
132 | 使用的时候注意与配置文件中注册的包名一致:
133 |
134 |
135 | ```
136 | val file = File(xxpath)
137 | val uri = FileProvider.getUriForFile(context, "com.alexlu.androidstorage.fileProvider", file);
138 | ```
139 |
140 |
141 | #### 为什么要建一个xml文件?
142 |
143 | 其实就是将以前的`file://`解析成自定义的名称,xml中的name参数就是你自定义的路径名称
144 | path填写文件夹名称,如果为空或者`/`,代表所有路径
145 |
146 |
147 | #### xml中不同方法的意义
148 |
149 | 以下是一一对应的:
150 | ```
151 | --> Context.getFilesDir()
152 | --> Context.getCacheDir()
153 | --> Environment.getExternalStorageDirectory()
154 | --> Context.getExternalFilesDir(String)
155 | --> Context.getExternalCacheDir()
156 | --> Context.getExternalMediaDirs()
157 | ```
158 | 我们看一下不同Api获取的路径是什么样子的:
159 |
160 | ```
161 | Log.d(TAG,Environment.getExternalStorageDirectory().absolutePath)
162 | ///storage/emulated/0
163 |
164 | Log.d(TAG,Environment.getRootDirectory().absolutePath)
165 | ///system
166 |
167 | Log.d(TAG,Environment.getDataDirectory().absolutePath)
168 | ///data
169 |
170 | Log.d(TAG,Environment.getDownloadCacheDirectory().absolutePath)
171 | ///data/cache
172 |
173 | if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
174 | Log.d(TAG,"getDownloadCacheDirectory():"+Environment.getStorageDirectory().absolutePath)
175 | ///storage
176 | }
177 |
178 | Log.d(TAG,this.filesDir.absolutePath)
179 | ///data/user/0/com.alexlu.androidstorage/files
180 |
181 | Log.d(TAG,this.cacheDir.absolutePath)
182 | ///data/user/0/com.alexlu.androidstorage/cache
183 |
184 | Log.d(TAG,this.codeCacheDir.absolutePath)
185 | ///data/user/0/com.alexlu.androidstorage/code_cache
186 |
187 | Log.d(TAG,"externalCacheDir:"+this.externalCacheDir?.absolutePath)
188 | ///storage/emulated/0/Android/data/com.alexlu.androidstorage/cache
189 |
190 | this.externalMediaDirs.forEach {
191 | Log.d(TAG,"externalMediaDirs:"+it.absolutePath)
192 | ///storage/emulated/0/Android/media/com.alexlu.androidstorage
193 | }
194 |
195 | Log.d(TAG,"getExternalFilesDir:"+this.getExternalFilesDir(null)?.absolutePath)
196 | ///storage/emulated/0/Android/data/com.alexlu.androidstorage/files
197 |
198 | ```
199 | 以上都标明了其输出路径,`storage/emulated/0`代表的就是外部存储空间,`/data/user/0`代表的就是内存存储空间,包含包名说明就是app私有目录或者分区存储目录。
200 |
201 | 我们通过以上方法就可以愉快的创建文件啦
202 |
203 | ## 使用示例:
204 |
205 | #### 使用内部私有目录
206 |
207 | 获取内存私有目录下的cache文件路径
208 | ```
209 | fun getAppCachePath(context: Context, subDir:String?=null):String{
210 | val path = StringBuilder(context.cacheDir.absolutePath)
211 | subDir?.let {
212 | path.append(File.separator).append(it).append(File.separator)
213 | }
214 | val dir = File(path.toString())
215 | if (!dir.exists()) dir.mkdir()
216 | return path.toString()
217 | }
218 |
219 | ```
220 |
221 | 获取内部私有目录下的files文件路径
222 |
223 | ```
224 | fun getAppFilePath(context: Context, subDir:String?=null): String {
225 | val path = StringBuilder(context.filesDir.absolutePath)
226 | subDir?.let {
227 | path.append(File.separator).append(it).append(File.separator)
228 | }
229 | val dir = File(path.toString())
230 | if (!dir.exists()) dir.mkdir()
231 | return path.toString()
232 | }
233 | ```
234 | 可以选择创建子目录,其中`subDis`代表子目录文件夹名称
235 |
236 | 我们保存两张图片到其目录下:
237 |
238 | ```
239 | //创建私有目录cache目录下文件
240 | val file = File(FileUtil.getAppCachePath(this),"${System.currentTimeMillis()}.jpg")
241 |
242 | //创建私有目录files->image目录下文件
243 | val file2 = File(FileUtil.getAppFilePath(this,"image"),"${System.currentTimeMillis()}.jpg")
244 |
245 | OperatePicUtil.saveBitmap2File(this,bitmap,file)
246 | OperatePicUtil.saveBitmap2File(this,bitmap,file2)
247 | ```
248 | (OperatePicUtil工具类可以查看[Demo](https://github.com/xluu233/AndroidStorageDemo))
249 |
250 | 我们在Android12虚拟机上可以看到保存没有问题:
251 |
252 |
253 |
254 |
255 | 
256 |
257 | #### 使用外部公共目录
258 |
259 | > `Environment.getExternalStorageDirectory()`在Android10之后标识为废弃,意思就是这个API很好用但是我不想让你用,实际测试在Android12上依旧有用。
260 | ```
261 | /**
262 | * TODO 外部目录-Pictures
263 | * @param subDir 子目录文件夹名称
264 | * @return
265 | */
266 | fun getExternalPicturesPath(subDir:String?=null): String{
267 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
268 | .append(File.separator)
269 | .append(Environment.DIRECTORY_PICTURES)
270 | subDir?.let {
271 | path.append(File.separator).append(it).append(File.separator)
272 | }
273 | val dir = File(path.toString())
274 | if (!dir.exists()) dir.mkdir()
275 | return path.toString()
276 | }
277 |
278 | /**
279 | * TODO 外部目录-Download
280 | * @param subDir 子目录文件夹名称
281 | * @return
282 | */
283 | fun getExternalDownloadPath(subDir:String?=null): String{
284 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
285 | .append(File.separator)
286 | .append(Environment.DIRECTORY_DOWNLOADS)
287 | subDir?.let {
288 | path.append(File.separator).append(it).append(File.separator)
289 | }
290 | val dir = File(path.toString())
291 | if (!dir.exists()) dir.mkdir()
292 | return path.toString()
293 | }
294 | ```
295 |
296 | #### 使用分区存储目录
297 |
298 | 接口定义:分别获取file,cache,media目录,type代表子目录名称,可以为null
299 |
300 | ```
301 | @Override
302 | public File getExternalFilesDir(String type) {
303 | return mBase.getExternalFilesDir(type);
304 | }
305 |
306 | @Override
307 | public File[] getExternalFilesDirs(String type) {
308 | return mBase.getExternalFilesDirs(type);
309 | }
310 |
311 | @Override
312 | public File getExternalCacheDir() {
313 | return mBase.getExternalCacheDir();
314 | }
315 |
316 | @Override
317 | public File[] getExternalCacheDirs() {
318 | return mBase.getExternalCacheDirs();
319 | }
320 |
321 | @Override
322 | public File[] getExternalMediaDirs() {
323 | return mBase.getExternalMediaDirs();
324 | }
325 |
326 | ```
327 |
328 | 获取分区存储目录:
329 | ```
330 | /**
331 | * TODO 分区存储-File目录
332 | * @param context
333 | * @param subDir 子目录文件夹名称
334 | * @return
335 | */
336 | fun getExternalAppFilePath(context: Context,subDir: String?=null):String{
337 | val path = context.getExternalFilesDir(subDir)?.absolutePath
338 | val dir = File(path.toString())
339 | if (!dir.exists()) dir.mkdir()
340 | return path.toString()
341 | }
342 |
343 | ```
344 | 保存图片到分区存储目录下:
345 |
346 | ```
347 | val file = File(FileUtil.getExternalAppFilePath(this),"${System.currentTimeMillis()}.jpg")
348 | PicturesUtil.saveBitmap2File(context = this,bitmap = bitmap,file = file)
349 |
350 | ```
351 | 我们可以打印文件的路径为:
352 |
353 | ```
354 | /sdcard/Android/data/com.alexlu.androidstorage/files
355 | ```
356 |
357 | **App设置界面中的“清除存储空间”和“清除缓存”**
358 |
359 | - 清除存储空间:清除app所有保存的文件和偏好设置,数据库等信息,但是不包括外部公共目录的文件,相当于App卸载重新安装了
360 | - 清除缓存:清除`外部分区存储`和`内部私有存储`中的 `cache` 目录
361 |
362 |
363 |
364 | ## 其他文件操作
365 |
366 | 比如其他类型的文件写入,保存文档、音频文件,插入图片到系统相册。具体用法请查看[Github Demo](https://github.com/xluu233/AndroidStorageDemo),如有错误,请大家指出,欢迎大家点个Star
--------------------------------------------------------------------------------
/app/src/main/java/com/alexlu/androidstorage/file/FilePath.kt:
--------------------------------------------------------------------------------
1 | package com.alexlu.androidstorage.util
2 |
3 | import android.app.Application
4 | import android.content.ContentResolver
5 | import android.content.Context
6 | import android.database.Cursor
7 | import android.net.Uri
8 | import android.os.Build
9 | import android.os.Environment
10 | import android.os.FileUtils
11 | import android.provider.MediaStore
12 | import android.webkit.MimeTypeMap
13 | import androidx.core.content.FileProvider
14 | import com.alexlu.androidstorage.App
15 | import java.io.*
16 | import kotlin.concurrent.thread
17 |
18 | /**
19 | * @ClassName FileUtil
20 | * @Description 文件工具类,包括获取文件目录,文件格式转换
21 | * @Author AlexLu_1406496344@qq.com
22 | * @Date 2021/4/15 10:54
23 | */
24 |
25 | fun getContext():Context{
26 | return App.instance
27 | }
28 |
29 | object FilePath {
30 |
31 | /*----------------------外部:分区存储目录------------------------*/
32 | /**
33 | * 分区存储-Cache目录
34 | */
35 | fun getAppExternalCachePath(subDir: String?=null):String{
36 | val path = StringBuilder(getContext().externalCacheDir?.absolutePath)
37 | subDir?.let {
38 | path.append(File.separator).append(it).append(File.separator)
39 | }
40 | val dir = File(path.toString())
41 | if (!dir.exists()) dir.mkdir()
42 | return path.toString()
43 | }
44 |
45 | /**
46 | * 分区存储-File目录
47 | */
48 | fun getAppExternalFilePath(subDir: String?=null):String{
49 | val path = getContext().getExternalFilesDir(subDir)?.absolutePath
50 | val dir = File(path.toString())
51 | if (!dir.exists()) dir.mkdir()
52 | return path.toString()
53 | }
54 | /*--------------------------------------------------*/
55 |
56 |
57 | /*-----------------------内部:私有目录--------------------------*/
58 |
59 | /**
60 | * 私有目录-files
61 | */
62 | fun getAppFilePath(subDir:String?=null): String {
63 | val path = StringBuilder(getContext().filesDir.absolutePath)
64 | subDir?.let {
65 | path.append(File.separator).append(it).append(File.separator)
66 | }
67 | val dir = File(path.toString())
68 | if (!dir.exists()) dir.mkdir()
69 | return path.toString()
70 | }
71 |
72 | /**
73 | * 私有目录-cache
74 | */
75 | fun getAppCachePath(subDir:String?=null):String{
76 | val path = StringBuilder(getContext().cacheDir.absolutePath)
77 | subDir?.let {
78 | path.append(File.separator).append(it).append(File.separator)
79 | }
80 | val dir = File(path.toString())
81 | if (!dir.exists()) dir.mkdir()
82 | return path.toString()
83 | }
84 |
85 | /*------------------------cache子目录------------------------*/
86 | fun getAudioPathEndWithSeparator(): String {
87 | return getAppCachePath("audio")
88 | }
89 |
90 | fun getTxtPathEndWithSeparator(): String {
91 | return getAppCachePath("txt")
92 | }
93 |
94 | fun getMp3PathEndWithSeparator(): String {
95 | return getAppCachePath("mp3")
96 | }
97 |
98 | fun getTempPathEndWithSeparator(): String {
99 | return getAppCachePath("temp")
100 | }
101 |
102 | /*--------------------------------------------------*/
103 |
104 |
105 |
106 | /*-----------------外部:公共目录(需要权限)----------------*/
107 | /**
108 | * Pictures
109 | */
110 | fun getExternalPicturesPath(subDir:String?=null): String{
111 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
112 | .append(File.separator)
113 | .append(Environment.DIRECTORY_PICTURES)
114 | subDir?.let {
115 | path.append(File.separator).append(it).append(File.separator)
116 | }
117 | val dir = File(path.toString())
118 | if (!dir.exists()) dir.mkdir()
119 | return path.toString()
120 | }
121 |
122 | /**
123 | * Download
124 | */
125 | fun getExternalDownloadPath(subDir:String?=null): String{
126 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
127 | .append(File.separator)
128 | .append(Environment.DIRECTORY_DOWNLOADS)
129 | subDir?.let {
130 | path.append(File.separator).append(it).append(File.separator)
131 | }
132 | val dir = File(path.toString())
133 | if (!dir.exists()) dir.mkdir()
134 | return path.toString()
135 | }
136 |
137 | /**
138 | * DCIM
139 | */
140 | fun getExternalCameraPath( subDir:String?=null): String{
141 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
142 | .append(File.separator)
143 | .append(Environment.DIRECTORY_DCIM)
144 | subDir?.let {
145 | path.append(File.separator).append(it).append(File.separator)
146 | }
147 | val dir = File(path.toString())
148 | if (!dir.exists()) dir.mkdir()
149 | return path.toString()
150 | }
151 |
152 | /**
153 | * Music
154 | */
155 | fun getExternalMusicPath(subDir:String?=null): String{
156 | val path = StringBuilder(Environment.getExternalStorageDirectory().absolutePath)
157 | .append(File.separator)
158 | .append(Environment.DIRECTORY_MUSIC)
159 | subDir?.let {
160 | path.append(File.separator).append(it).append(File.separator)
161 | }
162 | val dir = File(path.toString())
163 | if (!dir.exists()) dir.mkdir()
164 | return path.toString()
165 | }
166 | /*---------------------------------------------------------*/
167 |
168 |
169 | }
170 |
171 | object FileUtil{
172 |
173 | /**
174 | * File转Uri
175 | */
176 | fun file2Uri( file: File?): Uri?{
177 | if (file==null) return null
178 |
179 | return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
180 | //适配Android 7.0文件权限,通过FileProvider创建一个content类型的Uri
181 | FileProvider.getUriForFile(getContext(), "${getContext().packageName}.fileProvider", file)
182 | } else {
183 | Uri.fromFile(file)
184 | }
185 | }
186 |
187 |
188 | /**
189 | * 将文件转换成byte数组
190 | */
191 | fun file2Byte(file: File?): ByteArray? {
192 | if (file==null) return null
193 |
194 | var buffer: ByteArray? = null
195 | try {
196 | val fis = FileInputStream(file)
197 | val bos = ByteArrayOutputStream()
198 | val b = ByteArray(1024)
199 | var n: Int
200 | while (fis.read(b).also { n = it } != -1) {
201 | bos.write(b, 0, n)
202 | }
203 | fis.close()
204 | bos.close()
205 | buffer = bos.toByteArray()
206 | } catch (e: FileNotFoundException) {
207 | e.printStackTrace()
208 | } catch (e: IOException) {
209 | e.printStackTrace()
210 | }
211 | return buffer
212 | }
213 |
214 |
215 | /**
216 | * Uri转File
217 | */
218 | fun uri2File(uri: Uri?): File? {
219 | if (uri==null) return null
220 | var file:File ?= File(uri.toString())
221 | if (file!=null && file.exists()) return file
222 |
223 |
224 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
225 | when (uri.scheme) {
226 | ContentResolver.SCHEME_FILE -> {
227 | file = File(requireNotNull(uri.path))
228 | }
229 | ContentResolver.SCHEME_CONTENT -> {
230 | //把文件保存到沙盒
231 | val contentResolver = getContext().contentResolver
232 | val displayName = "${System.currentTimeMillis()}.${
233 | MimeTypeMap.getSingleton().getExtensionFromMimeType(
234 | contentResolver.getType(uri)
235 | )
236 | }".replace(".bin","")
237 | val ios = contentResolver.openInputStream(uri)
238 | if (ios != null) {
239 | file = File(FilePath.getTxtPathEndWithSeparator(), displayName).apply {
240 | val fos = FileOutputStream(this)
241 | FileUtils.copy(ios, fos)
242 | fos.close()
243 | ios.close()
244 | }
245 | }
246 | }
247 | else -> {
248 |
249 | }
250 | }
251 | return file
252 | }else{
253 | var path: String? = null
254 | when(uri.scheme){
255 | "file" -> {
256 | path = uri.encodedPath
257 | if (path != null) {
258 | path = Uri.decode(path)
259 | val cr = getContext().contentResolver
260 | val buff = StringBuffer()
261 | buff.append("(").append(MediaStore.Images.ImageColumns.DATA).append("=")
262 | .append("'$path'").append(")")
263 | val cur: Cursor? = cr.query(
264 | MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
265 | arrayOf(
266 | MediaStore.Images.ImageColumns._ID,
267 | MediaStore.Images.ImageColumns.DATA
268 | ),
269 | buff.toString(),
270 | null,
271 | null
272 | )
273 | var index = 0
274 | var dataIdx = 0
275 | cur?.let {
276 | cur.moveToFirst()
277 | while (!cur.isAfterLast()) {
278 | index = cur.getColumnIndex(MediaStore.Images.ImageColumns._ID)
279 | index = cur.getInt(index)
280 | dataIdx = cur.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
281 | path = cur.getString(dataIdx)
282 | cur.moveToNext()
283 | }
284 | cur.close()
285 | }
286 | if (index == 0) {
287 | } else {
288 | val u = Uri.parse("content://media/external/images/media/$index")
289 | println("temp uri is :$u")
290 | }
291 | }
292 | }
293 | "content" -> {
294 | // 4.2.2以后
295 | val proj = arrayOf(MediaStore.Images.Media.DATA)
296 | val cursor: Cursor? = getContext().contentResolver.query(uri, proj, null, null, null)
297 | cursor?.let {
298 | if (cursor.moveToFirst()) {
299 | val columnIndex: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
300 | path = cursor.getString(columnIndex)
301 | }
302 | cursor.close()
303 | }
304 | }
305 | else -> {
306 | //Log.i(TAG, "Uri Scheme:" + uri.getScheme());
307 | }
308 | }
309 | return File(path)
310 | }
311 | }
312 |
313 | /**
314 | * 删除文件夹
315 | */
316 | fun deleteRecursive(fileOrDirectory: File) {
317 | if (fileOrDirectory.isDirectory) for (child in fileOrDirectory.listFiles()) deleteRecursive(
318 | child
319 | )
320 | fileOrDirectory.delete()
321 | }
322 |
323 | fun deleteCacheDir() = thread{
324 | File(FilePath.getTempPathEndWithSeparator()).deleteRecursively()
325 | File(FilePath.getMp3PathEndWithSeparator()).deleteRecursively()
326 | File(FilePath.getTxtPathEndWithSeparator()).deleteRecursively()
327 | File(FilePath.getAudioPathEndWithSeparator()).deleteRecursively()
328 | }
329 |
330 | }
331 |
--------------------------------------------------------------------------------