? {
114 | return if (SDK_INT >= KITKAT) {
115 | context.getExternalFilesDirs(null)
116 | } else {
117 | context.getExternalFilesDir(null)?.listFiles()
118 | }
119 | }
120 | }
--------------------------------------------------------------------------------
/docs/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 |
2 | # 👮🏼 Contributor Covenant Code of Conduct
3 |
4 | ## 🏳️ Our Pledge
5 |
6 | We as members, contributors, and leaders pledge to make participation in our
7 | community a harassment-free experience for everyone, regardless of age, body
8 | size, visible or invisible disability, ethnicity, sex characteristics, gender
9 | identity and expression, level of experience, education, socio-economic status,
10 | nationality, personal appearance, race, religion, or sexual identity
11 | and orientation.
12 |
13 | We pledge to act and interact in ways that contribute to an open, welcoming,
14 | diverse, inclusive, and healthy community.
15 |
16 | ## 🤖 Our Standards
17 |
18 | Examples of behavior that contributes to a positive environment for our
19 | community include:
20 |
21 | * Demonstrating empathy and kindness toward other people
22 | * Being respectful of differing opinions, viewpoints, and experiences
23 | * Giving and gracefully accepting constructive feedback
24 | * Accepting responsibility and apologizing to those affected by our mistakes,
25 | and learning from the experience
26 | * Focusing on what is best not just for us as individuals, but for the
27 | overall community
28 |
29 | Examples of unacceptable behavior include:
30 |
31 | * The use of sexualized language or imagery, and sexual attention or
32 | advances of any kind
33 | * Trolling, insulting or derogatory comments, and personal or political attacks
34 | * Public or private harassment
35 | * Publishing others' private information, such as a physical or email
36 | address, without their explicit permission
37 | * Other conduct which could reasonably be considered inappropriate in a
38 | professional setting
39 |
40 | ## 📢 Enforcement Responsibilities
41 |
42 | Community leaders are responsible for clarifying and enforcing our standards of
43 | acceptable behavior and will take appropriate and fair corrective action in
44 | response to any behavior that they deem inappropriate, threatening, offensive,
45 | or harmful.
46 |
47 | Community leaders have the right and responsibility to remove, edit, or reject
48 | comments, commits, code, wiki edits, issues, and other contributions that are
49 | not aligned to this Code of Conduct, and will communicate reasons for moderation
50 | decisions when appropriate.
51 |
52 | ## 🌎 Scope
53 |
54 | This Code of Conduct applies within all community spaces, and also applies when
55 | an individual is officially representing the community in public spaces.
56 | Examples of representing our community include using an official e-mail address,
57 | posting via an official social media account, or acting as an appointed
58 | representative at an online or offline event.
59 |
60 | ## 📝 Enforcement
61 |
62 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
63 | reported to the community leaders responsible for enforcement at
64 | murillo_comino@hotmail.com.
65 | All complaints will be reviewed and investigated promptly and fairly.
66 |
67 | All community leaders are obligated to respect the privacy and security of the
68 | reporter of any incident.
69 |
70 | ## 🚨 Enforcement Guidelines
71 |
72 | Community leaders will follow these Community Impact Guidelines in determining
73 | the consequences for any action they deem in violation of this Code of Conduct:
74 |
75 | ### 1. Correction
76 |
77 | **Community Impact**: Use of inappropriate language or other behavior deemed
78 | unprofessional or unwelcome in the community.
79 |
80 | **Consequence**: A private, written warning from community leaders, providing
81 | clarity around the nature of the violation and an explanation of why the
82 | behavior was inappropriate. A public apology may be requested.
83 |
84 | ### 2. Warning
85 |
86 | **Community Impact**: A violation through a single incident or series
87 | of actions.
88 |
89 | **Consequence**: A warning with consequences for continued behavior. No
90 | interaction with the people involved, including unsolicited interaction with
91 | those enforcing the Code of Conduct, for a specified period of time. This
92 | includes avoiding interactions in community spaces as well as external channels
93 | like social media. Violating these terms may lead to a temporary or
94 | permanent ban.
95 |
96 | ### 3. Temporary Ban
97 |
98 | **Community Impact**: A serious violation of community standards, including
99 | sustained inappropriate behavior.
100 |
101 | **Consequence**: A temporary ban from any sort of interaction or public
102 | communication with the community for a specified period of time. No public or
103 | private interaction with the people involved, including unsolicited interaction
104 | with those enforcing the Code of Conduct, is allowed during this period.
105 | Violating these terms may lead to a permanent ban.
106 |
107 | ### 4. Permanent Ban
108 |
109 | **Community Impact**: Demonstrating a pattern of violation of community
110 | standards, including sustained inappropriate behavior, harassment of an
111 | individual, or aggression toward or disparagement of classes of individuals.
112 |
113 | **Consequence**: A permanent ban from any sort of public interaction within
114 | the community.
115 |
116 | ## Attribution
117 |
118 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
119 | version 2.0, available at [here](https://www.contributor-covenant.org/version/2/0/code_of_conduct.html).
120 |
121 | [homepage]: https://www.contributor-covenant.org
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/handle-path-oz/src/main/java/br/com/onimur/handlepathoz/utils/FileUtils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 22/06/20 17:50
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 21/06/20 00:13
9 | */
10 |
11 | package br.com.onimur.handlepathoz.utils
12 |
13 | import android.content.ContentResolver
14 | import android.content.Context
15 | import android.net.Uri
16 | import android.provider.OpenableColumns
17 | import br.com.onimur.handlepathoz.utils.Constants.PathUri.FOLDER_DOWNLOAD
18 | import br.com.onimur.handlepathoz.utils.ContentUriUtils.getCursor
19 | import br.com.onimur.handlepathoz.utils.extension.logD
20 | import br.com.onimur.handlepathoz.utils.extension.logE
21 | import kotlinx.coroutines.Job
22 | import kotlinx.coroutines.ensureActive
23 | import java.io.File
24 | import java.io.FileOutputStream
25 |
26 | internal object FileUtils {
27 |
28 | /**
29 | * Method that downloads the file to an internal folder at the root of the project.
30 | * For cases where the file has an unknown provider, cloud files and for users using
31 | * third-party file explorer api.
32 | *
33 | * @param uri of the file
34 | * @return new path string
35 | */
36 | fun downloadFile(
37 | contentResolver: ContentResolver,
38 | file: File,
39 | uri: Uri,
40 | job: Job?
41 | ): Boolean {
42 | try {
43 | val inputStream = contentResolver.openInputStream(uri)
44 | inputStream?.use { input ->
45 | logD("${input.available()}")
46 | FileOutputStream(file).use { output ->
47 | job?.ensureActive()
48 | val buffer = ByteArray(1024)
49 | var read: Int = input.read(buffer)
50 | logD("Copying ${file.name}")
51 | while (read != -1) {
52 | job?.ensureActive()
53 | output.write(buffer, 0, read)
54 | read = input.read(buffer)
55 | }
56 | }
57 | }
58 | } catch (e: Exception) {
59 | file.deleteRecursively()
60 | logE("Task canceled with exception ${e.message} and file ${file.name} deleted")
61 | throw e
62 | }
63 | logD("File and Path copied - ${file.name}")
64 | return true
65 | }
66 |
67 |
68 | fun getFullPathTemp(context: Context, uri: Uri): String {
69 | val folder: File? = context.getExternalFilesDir("Temp")
70 | return "${folder.toString()}/${getFileName(context, uri)}"
71 | }
72 |
73 |
74 | private fun getFileName(context: Context, uri: Uri): String? {
75 | var result: String? = null
76 |
77 | uri.scheme?.let {
78 | if (it == "content") {
79 | getCursor(context.contentResolver, uri)?.use { cursor ->
80 | if (cursor.moveToFirst()) {
81 | result =
82 | cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
83 | }
84 | }
85 | }
86 | }
87 | if (result == null) {
88 | result = uri.path
89 | val cut = result?.lastIndexOf('/') ?: -1
90 | if (cut != -1) {
91 | result = result?.substring(cut.plus(1))
92 | }
93 | }
94 | return result
95 | }
96 |
97 | /**
98 | * Returns subfolder from the main folder to the file location or empty string
99 | * EXAMPLE:
100 | * Input uriString = "content://com.android.providers.downloads.documents/document/raw%3%2Fstorage%2Femulated%2F0%2FDownload%2FsubFolder%2FsubFolder2%2Ffile.jpg"
101 | * Input folderRoot = "Download"
102 | * Output: subFolder/subFolder2/
103 | *
104 | * @param uriString Path file
105 | * @param folderRoot It is usually "Download"
106 | */
107 | fun getSubFolders(uriString: String, folderRoot: String = FOLDER_DOWNLOAD) =
108 | uriString
109 | .replace("%2F", "/")
110 | .replace("%20", " ")
111 | .replace("%3A", ":")
112 | .split("/")
113 | .run {
114 | val indexRoot = indexOf(folderRoot)
115 | if (folderRoot.isNotBlank().and(indexRoot != -1)) {
116 | subList(indexRoot + 1, lastIndex)
117 | .joinToString(separator = "") { "$it/" }
118 | } else {
119 | ""
120 | }
121 | }
122 |
123 | /**
124 | * Delete the files in the "Temp" folder at the root of the project.
125 | *
126 | */
127 | fun deleteTemporaryFiles(context: Context) {
128 | context.getExternalFilesDir("Temp")?.let { folder ->
129 | folder.listFiles()?.let { files ->
130 | files.forEach {
131 | if (it.deleteRecursively()) {
132 | logD("${it.absoluteFile} delete file was called")
133 | } else {
134 | logE("${it.absoluteFile} there is no file")
135 | }
136 | }
137 | }
138 | }
139 | }
140 | }
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
18 |
22 |
24 |
25 |
31 |
32 |
33 |
34 |
35 |
36 |
39 |
42 |
43 |
49 |
50 |
51 |
52 |
53 |
54 |
57 |
61 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/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/layout/row_real_path.xml:
--------------------------------------------------------------------------------
1 |
10 |
17 |
18 |
22 |
23 |
26 |
27 |
32 |
33 |
42 |
43 |
57 |
58 |
59 |
67 |
68 |
80 |
81 |
92 |
93 |
105 |
106 |
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 📚 Handle Path Oz
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 |
31 |
32 |
33 | Android library written in Kotlin, but can be used in Java too. Built to handle a single or multiple Uri (paths) received through Intents.
34 |
35 | When you retrieve a Uri through an intent, its path is defined in relation to the File Chooser used, which does not represent the actual path of the file, making it impossible to work with it. This library aims to retrieve the real path of any file in a simple way, and then it is possible to use it for its proper purpose.
36 |
37 | Compatible with API version from 16.
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | ## 💞 Support us
46 |
47 | We are developing this structure in the open source community without financial planning.
48 | If you like this project and would like to help us, make a donation:
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | ## 📝 Content
63 |
64 | - [Sample application](#-sample-application)
65 | - [Config](#%EF%B8%8F-config)
66 | - [Getting start](#-getting-start)
67 | - [Multiple uri](#working-with-multiple-uri)
68 | - [Kotlin](#-kotlin)
69 | - [Java](#-java)
70 | - [Single uri](#working-with-single-uri)
71 | - [Kotlin](#-kotlin-1)
72 | - [Java](#-java-1)
73 | - [Projects using this library](#-projects-using-this-library)
74 | - [Main features](#-main-features)
75 | - [Built with](#-built-with)
76 | - [Contributing](#-contributing)
77 | - [License](#-license)
78 |
79 | ## 📱 Sample application
80 |
81 |
82 |
83 |
84 |
85 | ### 🌱 Download release
86 |
87 | You can download the sample application with the latest release [here](artifacts/HandlePathOZ.apk).
88 |
89 | ### 🌱 Install by GooglePlay
90 |
91 | Check the Sample App on GooglePlay
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 | ## 🛠️ Config
100 |
101 | First check the latest [version](https://bintray.com/onimur/maven/HandlePathOz/_latestVersion).
102 |
103 | ### Gradle
104 |
105 | In build.gradle(Module:app) within dependencies, implement:
106 |
107 | ```kotlin
108 |
109 | implementation 'com.github.onimur:handle-path-oz:1.0.7'
110 |
111 | ```
112 |
113 | ### Maven
114 |
115 | ```
116 |
117 |
118 | com.github.onimur
119 | handle-path-oz
120 | 1.0.7
121 | pom
122 |
123 |
124 | ```
125 |
126 | ### Ivy
127 |
128 | ```
129 |
130 |
131 |
132 |
133 |
134 | ```
135 |
136 | ## 💡 Getting start
137 |
138 | ### Working with Multiple uri
139 |
140 | The next steps are for working with multiple uri as well as for a single uri.
141 |
142 | #### 🎲 Kotlin
143 |
144 | You can check in the wikipage, [click here](https://github.com/onimur/handle-path-oz/wiki/Kotlin---Multiple-Uri).
145 |
146 | #### 🎲 Java
147 |
148 | You can check in the wikipage, [click here](https://github.com/onimur/handle-path-oz/wiki/Java---Multiple-Uri).
149 |
150 | ### Working with Single uri
151 |
152 | The next steps only serve to work with a single uri.
153 |
154 | #### 🎲 Kotlin
155 |
156 | You can check in the wikipage, [click here](https://github.com/onimur/handle-path-oz/wiki/Kotlin-Single-Uri).
157 |
158 | #### 🎲 Java
159 |
160 | You can check in the wikipage, [click here](https://github.com/onimur/handle-path-oz/wiki/Java-Single-Uri).
161 |
162 | ## 🚀 Projects using this library
163 |
164 | Here's a [wikipage list of projects](https://github.com/onimur/handle-path-oz/wiki/Projects-using-HandlePathOz).
165 |
166 | If you've used this library, please let me know! Nothing makes me happier than seeing someone else take my work and go wild with it.
167 |
168 | ## 🔍 Main features
169 |
170 | - [Kotlin Coroutines/Flow](https://kotlinlang.org/docs/reference/coroutines-overview.html)
171 | - Parse Uri
172 | - Multiple tasks in parallel
173 |
174 | ## 📐 Built with
175 |
176 | * [Android Studio 4.0](https://developer.android.com/studio)
177 |
178 | ## 🧩 Contributing
179 |
180 | This project is open-source, so feel free to fork, or to share your ideas and changes to improve the project, check with more details below.
181 |
182 | - 💬 [Contributing](docs/CONTRIBUTING.md)
183 | - 👮🏼 [Code of conduct](docs/CODE_OF_CONDUCT.md)
184 | - 😷 [Support](docs/SUPPORT.md)
185 |
186 | ## 📃 License
187 |
188 | Copyright (c) 2020, HandlePathOz.
189 |
190 | Licensed under the Apache License, Version 2.0 (the "License");
191 | you may not use this file except in compliance with the License.
192 | You may obtain a copy of the License at
193 |
194 | http://www.apache.org/licenses/LICENSE-2.0
195 |
196 | Unless required by applicable law or agreed to in writing, software
197 | distributed under the License is distributed on an "AS IS" BASIS,
198 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
199 | See the License for the specific language governing permissions and
200 | limitations under the License.
201 |
202 | * [Apache License 2.0](./LICENSE)
203 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_single_uri.xml:
--------------------------------------------------------------------------------
1 |
10 |
11 |
17 |
18 |
24 |
25 |
36 |
37 |
45 |
46 |
50 |
51 |
55 |
56 |
62 |
63 |
69 |
70 |
75 |
76 |
83 |
84 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
110 |
111 |
119 |
120 |
124 |
125 |
129 |
130 |
136 |
137 |
143 |
144 |
149 |
150 |
157 |
158 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
185 |
186 |
--------------------------------------------------------------------------------
/handle-path-oz/src/main/java/br/com/onimur/handlepathoz/utils/HandlePathOzUtils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 29/07/20 14:47
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 29/07/20 14:36
9 | */
10 |
11 | package br.com.onimur.handlepathoz.utils
12 |
13 | import android.content.Context
14 | import android.net.Uri
15 | import android.os.Build.VERSION.SDK_INT
16 | import android.os.Build.VERSION_CODES.KITKAT
17 | import br.com.onimur.handlepathoz.HandlePathOzListener
18 | import br.com.onimur.handlepathoz.errors.HandlePathOzListenerException
19 | import br.com.onimur.handlepathoz.model.PathOz
20 | import br.com.onimur.handlepathoz.utils.Constants.HandlePathOz.BELOW_KITKAT_FILE
21 | import br.com.onimur.handlepathoz.utils.Constants.HandlePathOz.CLOUD_FILE
22 | import br.com.onimur.handlepathoz.utils.Constants.HandlePathOz.LOCAL_PROVIDER
23 | import br.com.onimur.handlepathoz.utils.Constants.HandlePathOz.UNKNOWN_FILE_CHOOSER
24 | import br.com.onimur.handlepathoz.utils.Constants.HandlePathOz.UNKNOWN_PROVIDER
25 | import br.com.onimur.handlepathoz.utils.FileUtils.deleteTemporaryFiles
26 | import br.com.onimur.handlepathoz.utils.FileUtils.downloadFile
27 | import br.com.onimur.handlepathoz.utils.FileUtils.getFullPathTemp
28 | import br.com.onimur.handlepathoz.utils.PathUtils.getPathAboveKitKat
29 | import br.com.onimur.handlepathoz.utils.PathUtils.getPathBelowKitKat
30 | import br.com.onimur.handlepathoz.utils.extension.*
31 | import kotlinx.coroutines.*
32 | import kotlinx.coroutines.flow.*
33 | import java.io.File
34 | import kotlin.system.measureTimeMillis
35 |
36 | internal class HandlePathOzUtils(
37 | private val context: Context,
38 | private val listener: HandlePathOzListener
39 | ) {
40 | private val mainScope = MainScope()
41 | private var job: Job? = null
42 | private val isKitKat = SDK_INT >= KITKAT
43 |
44 | @FlowPreview
45 | fun getListRealPath(listUri: List, concurrency: Int) {
46 | if (listener is HandlePathOzListener.MultipleUri) {
47 | val list = mutableListOf()
48 | var error: Throwable? = null
49 | job = mainScope.launch {
50 | try {
51 | listener.onLoading(0)
52 | logD("Launch Job")
53 | val time = measureTimeMillis {
54 | listUri.asFlow()
55 | .flatMapMerge(concurrency) { uri ->
56 | flow { emit(getPath(uri)) }
57 | .flowOn(Dispatchers.IO)
58 | }.collectIndexed { index, pair ->
59 | list.add(pair)
60 | listener.onLoading(index + 1)
61 | }
62 | }
63 | logD("Total task time: $time ms")
64 | } catch (tr: Throwable) {
65 | error = tr
66 | logE("$tr - ${tr.message}")
67 | } finally {
68 | if (mainScope.isActive) {
69 | //so Activity is active
70 | listener.onRequestHandlePathOz(list, error)
71 | }
72 | logD(
73 | "MainScope isActive: ${mainScope.isActive}" +
74 | "\nThis Scope isActive: ${this.isActive}" +
75 | "\nJob isNew: ${job?.isNew}" +
76 | "\nJob isCompleting: ${job?.isCompleting}" +
77 | "\nJob isCancelling: ${job?.isCancelling}" +
78 | "\nJob wasCancelled: ${job?.wasCancelled}" +
79 | "\nJob wasCompleted: ${job?.wasCompleted}"
80 | )
81 | }
82 | }
83 | } else {
84 | throw HandlePathOzListenerException("If you are working with single uri, use the interface: HandlePathOzListener.SingleUri")
85 | }
86 | }
87 |
88 | fun getRealPath(uri: Uri) {
89 | if (listener is HandlePathOzListener.SingleUri) {
90 | var error: Throwable? = null
91 | var pathOz = PathOz("", "")
92 | job = mainScope.launch {
93 | try {
94 | logD("Launch Job")
95 | val time = measureTimeMillis {
96 | pathOz = flow { emit(getPath(uri)) }
97 | .flowOn(Dispatchers.IO)
98 | .single()
99 | }
100 | logD("Total task time: $time ms")
101 | } catch (tr: Throwable) {
102 | error = tr
103 | logE("$tr - ${tr.message}")
104 | } finally {
105 | if (mainScope.isActive) {
106 | //so Activity is active
107 | listener.onRequestHandlePathOz(pathOz, error)
108 | }
109 | logD(
110 | "MainScope isActive: ${mainScope.isActive}" +
111 | "\nThis Scope isActive: ${this.isActive}" +
112 | "\nJob isNew: ${job?.isNew}" +
113 | "\nJob isCompleting: ${job?.isCompleting}" +
114 | "\nJob isCancelling: ${job?.isCancelling}" +
115 | "\nJob wasCancelled: ${job?.wasCancelled}" +
116 | "\nJob wasCompleted: ${job?.wasCompleted}"
117 | )
118 | }
119 | }
120 | } else {
121 | throw HandlePathOzListenerException("If you are working with multiple uri's, use the interface: HandlePathOzListener.MultipleUri")
122 | }
123 | }
124 |
125 | private fun getPath(uri: Uri): PathOz {
126 | val contentResolver = context.contentResolver
127 | val pathTempFile = getFullPathTemp(context, uri)
128 | val file: File?
129 | return if (isKitKat) {
130 | val returnedPath = getPathAboveKitKat(context, uri)
131 | when {
132 | //Cloud
133 | uri.isCloudFile -> {
134 | file = File(pathTempFile)
135 | downloadFile(contentResolver, file, uri, job)
136 | PathOz(CLOUD_FILE, pathTempFile).alsoLogD()
137 | }
138 | //Third Party App
139 | returnedPath.isBlank() -> {
140 | file = File(pathTempFile)
141 | downloadFile(contentResolver, file, uri, job)
142 | PathOz(UNKNOWN_FILE_CHOOSER, pathTempFile).alsoLogD()
143 | }
144 | //Unknown Provider or unknown mime type
145 | uri.isUnknownProvider(returnedPath, contentResolver) -> {
146 | file = File(pathTempFile)
147 | downloadFile(contentResolver, file, uri, job)
148 | PathOz(UNKNOWN_PROVIDER, pathTempFile).alsoLogD()
149 | }
150 | //LocalFile
151 | else -> {
152 | PathOz(LOCAL_PROVIDER, returnedPath).alsoLogD()
153 | }
154 | }
155 | } else {
156 | PathOz(
157 | BELOW_KITKAT_FILE,
158 | getPathBelowKitKat(context, uri)
159 | ).alsoLogD()
160 | }
161 | }
162 |
163 | fun cancelTask() {
164 | job?.let {
165 | if (it.isActive) {
166 | it.cancel()
167 | logD("\nJob isActive: ${it.isActive}\nJob isCancelled: ${it.isCancelled}\nJob isCompleted: ${it.isCompleted}")
168 | }
169 | }
170 | }
171 |
172 | fun onDestroy() {
173 | if (mainScope.isActive) {
174 | mainScope.cancel()
175 | }
176 | }
177 |
178 | fun deleteTemporaryFiles() {
179 | deleteTemporaryFiles(context)
180 | }
181 | }
--------------------------------------------------------------------------------
/app/src/main/java/br/com/onimur/sample/handlepathoz/kotlin/SingleUriActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 27/07/20 15:18
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 27/07/20 14:36
9 | */
10 |
11 | package br.com.onimur.sample.handlepathoz.kotlin
12 |
13 | import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
14 | import android.app.Activity
15 | import android.content.Intent
16 | import android.content.Intent.ACTION_PICK
17 | import android.content.pm.PackageManager.PERMISSION_GRANTED
18 | import android.os.Bundle
19 | import android.os.Environment
20 | import android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
21 | import android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI
22 | import android.widget.Button
23 | import android.widget.TextView
24 | import android.widget.Toast
25 | import androidx.appcompat.app.AppCompatActivity
26 | import androidx.core.app.ActivityCompat
27 | import androidx.core.content.ContextCompat
28 | import br.com.comino.sample.handlepathoz.R
29 | import br.com.onimur.handlepathoz.HandlePathOz
30 | import br.com.onimur.handlepathoz.HandlePathOzListener
31 | import br.com.onimur.handlepathoz.model.PathOz
32 | import kotlinx.coroutines.FlowPreview
33 |
34 | class SingleUriActivity : AppCompatActivity(R.layout.activity_single_uri),
35 | HandlePathOzListener.SingleUri {
36 |
37 | companion object {
38 | const val REQUEST_PERMISSION = 123
39 | const val REQUEST_OPEN_GALLERY = 1111
40 | }
41 |
42 | private lateinit var buttonOpen: Button
43 | private lateinit var tvOriginalPath: TextView
44 | private lateinit var tvOriginalType: TextView
45 | private lateinit var tvRealPath: TextView
46 | private lateinit var tvRealType: TextView
47 | private lateinit var progressLoading: ProgressDialog
48 | private lateinit var progressCancelling: ProgressDialog
49 | private lateinit var handlePathOz: HandlePathOz
50 |
51 | override fun onCreate(savedInstanceState: Bundle?) {
52 | super.onCreate(savedInstanceState)
53 | //
54 | init()
55 | startAction()
56 | //
57 | }
58 |
59 | private fun init() {
60 | initButton()
61 | initTextViews()
62 | initProgressBar()
63 | initHandlePathOz()
64 | }
65 |
66 | private fun startAction() {
67 | startButton()
68 | startProgressBar()
69 | }
70 |
71 | ////////////////////////////////////// INIT /////////////////////////////////////////////
72 | private fun initButton() {
73 | buttonOpen = findViewById(R.id.btn_open)
74 | }
75 |
76 | private fun initTextViews() {
77 | tvOriginalPath = findViewById(R.id.tv_original_path)
78 | tvOriginalType = findViewById(R.id.tv_original_type)
79 | tvRealPath = findViewById(R.id.tv_real_path)
80 | tvRealType = findViewById(R.id.tv_real_type)
81 | }
82 |
83 | private fun initProgressBar() {
84 | progressLoading = ProgressDialog(this, getString(R.string.validating)).apply {
85 | setCancelable(true)
86 | create()
87 | }
88 |
89 | progressCancelling = ProgressDialog(this, getString(R.string.cancelling)).apply {
90 | setCancelable(false)
91 | create()
92 | }
93 | }
94 |
95 | private fun initHandlePathOz() {
96 | //initialize library
97 | handlePathOz = HandlePathOz(this, this)
98 | }
99 |
100 | ////////////////////////////////////// START ////////////////////////////////////////////
101 | private fun startButton() {
102 | buttonOpen.setOnClickListener { openFile() }
103 | }
104 |
105 | private fun startProgressBar() {
106 | progressLoading.setOnCancelListener {
107 | //Call progress to cancel task
108 | if (!progressCancelling.isShowing) {
109 | progressCancelling.show()
110 | }
111 | //cancelTask
112 | handlePathOz.cancelTask()
113 |
114 | }
115 | }
116 |
117 | ////////////////////////////////////// OTHER METHODS /////////////////////////////////////
118 | private fun openFile() {
119 | if (checkSelfPermission()) {
120 | val intent =
121 | if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
122 | Intent(ACTION_PICK, EXTERNAL_CONTENT_URI)
123 | } else {
124 | Intent(ACTION_PICK, INTERNAL_CONTENT_URI)
125 | }
126 |
127 | intent.apply {
128 | type = "*/*"
129 | action = Intent.ACTION_GET_CONTENT
130 | action = Intent.ACTION_OPEN_DOCUMENT
131 | addCategory(Intent.CATEGORY_OPENABLE)
132 | putExtra("return-data", true)
133 | addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
134 | }
135 | startActivityForResult(intent, REQUEST_OPEN_GALLERY)
136 | }
137 | }
138 |
139 | private fun checkSelfPermission(): Boolean {
140 | if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE)
141 | != PERMISSION_GRANTED
142 | ) {
143 | ActivityCompat.requestPermissions(
144 | this,
145 | arrayOf(WRITE_EXTERNAL_STORAGE),
146 | REQUEST_PERMISSION
147 | )
148 | return false
149 | }
150 | return true
151 | }
152 |
153 | ///////////////////////////// OVERRIDE METHODS //////////////////////////////////////////
154 | override fun onRequestPermissionsResult(
155 | requestCode: Int,
156 | permissions: Array,
157 | grantResults: IntArray
158 | ) {
159 | if (requestCode == REQUEST_PERMISSION) {
160 | if (grantResults[0] == PERMISSION_GRANTED) {
161 | openFile()
162 | } else {
163 | TODO("show Message to the user")
164 | }
165 | }
166 | }
167 |
168 | @FlowPreview
169 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
170 | super.onActivityResult(requestCode, resultCode, data)
171 | if ((requestCode == REQUEST_OPEN_GALLERY) and (resultCode == Activity.RESULT_OK)) {
172 |
173 | data?.data?.also { it ->
174 | //Update TextView with Original path
175 | tvOriginalPath.text = it.path
176 | tvOriginalType.text = "Unknown"
177 |
178 | //set uri to handle
179 | handlePathOz.getRealPath(it)
180 | //show Progress Loading
181 | if (!progressLoading.isShowing) {
182 | progressLoading.show()
183 | }
184 | }
185 |
186 |
187 | }
188 | }
189 |
190 | override fun onBackPressed() {
191 | with(handlePathOz) {
192 | //Cancel the task if it is working.
193 | cancelTask()
194 | //Deletes temporary files
195 | deleteTemporaryFiles()
196 | }
197 | super.onBackPressed()
198 | }
199 |
200 | override fun onDestroy() {
201 | with(handlePathOz) {
202 | onDestroy()
203 | deleteTemporaryFiles()
204 | }
205 | super.onDestroy()
206 | }
207 |
208 |
209 | ///////////////////////////// LISTENER HANDLE PATH OZ ///////////////////////////////////
210 | override fun onRequestHandlePathOz(pathOz: PathOz, tr: Throwable?) {
211 | //Hide Progress
212 | if (progressLoading.isShowing or progressCancelling.isShowing) {
213 | progressLoading.dismiss()
214 | progressCancelling.dismiss()
215 | }
216 | //Update TextView with RealPath
217 | tvRealPath.text = pathOz.path
218 | tvRealType.text = pathOz.type
219 |
220 | //Handle Exception (Optional)
221 | tr?.let {
222 | Toast.makeText(this, "${it.message}", Toast.LENGTH_SHORT).show()
223 | }
224 | }
225 | }
226 |
--------------------------------------------------------------------------------
/app/src/main/java/br/com/onimur/sample/handlepathoz/java/SingleUriActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 27/07/20 15:18
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 27/07/20 15:16
9 | */
10 |
11 | package br.com.onimur.sample.handlepathoz.java;
12 |
13 | import android.Manifest;
14 | import android.content.Intent;
15 | import android.content.pm.PackageManager;
16 | import android.net.Uri;
17 | import android.os.Bundle;
18 | import android.os.Environment;
19 | import android.widget.Button;
20 | import android.widget.TextView;
21 | import android.widget.Toast;
22 |
23 | import androidx.annotation.NonNull;
24 | import androidx.appcompat.app.AppCompatActivity;
25 | import androidx.core.app.ActivityCompat;
26 | import androidx.core.content.ContextCompat;
27 |
28 | import org.jetbrains.annotations.NotNull;
29 | import org.jetbrains.annotations.Nullable;
30 |
31 | import br.com.comino.sample.handlepathoz.R;
32 | import br.com.onimur.handlepathoz.HandlePathOz;
33 | import br.com.onimur.handlepathoz.HandlePathOzListener;
34 | import br.com.onimur.handlepathoz.model.PathOz;
35 | import br.com.onimur.sample.handlepathoz.kotlin.ProgressDialog;
36 |
37 | import static android.content.Intent.ACTION_PICK;
38 | import static android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
39 | import static android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI;
40 |
41 | public class SingleUriActivity extends AppCompatActivity implements HandlePathOzListener.SingleUri {
42 |
43 | private static final int REQUEST_PERMISSION = 123;
44 | private static final int REQUEST_OPEN_GALLERY = 1111;
45 |
46 | private Button buttonOpen;
47 | private TextView tvOriginalPath;
48 | private TextView tvOriginalType;
49 | private TextView tvRealPath;
50 | private TextView tvRealType;
51 | private ProgressDialog progressLoading;
52 | private ProgressDialog progressCancelling;
53 | private HandlePathOz handlePathOz;
54 |
55 | @Override
56 | protected void onCreate(Bundle savedInstanceState) {
57 | super.onCreate(savedInstanceState);
58 | setContentView(R.layout.activity_single_uri);
59 |
60 | init();
61 | startAction();
62 | }
63 |
64 | private void init() {
65 | initButton();
66 | initTextView();
67 | initProgressBar();
68 | initHandlePathOz();
69 | }
70 |
71 | private void startAction() {
72 | startButton();
73 | startProgressBar();
74 | }
75 |
76 | ////////////////////////////////////// INIT /////////////////////////////////////////////
77 | private void initButton() {
78 | buttonOpen = findViewById(R.id.btn_open);
79 | }
80 |
81 | private void initTextView() {
82 | tvOriginalPath = findViewById(R.id.tv_original_path);
83 | tvOriginalType = findViewById(R.id.tv_original_type);
84 | tvRealPath = findViewById(R.id.tv_real_path);
85 | tvRealType = findViewById(R.id.tv_real_type);
86 | }
87 |
88 | private void initProgressBar() {
89 | progressLoading = new ProgressDialog(this, getString(R.string.validating));
90 | progressLoading.setCancelable(true);
91 | progressLoading.create();
92 |
93 | progressCancelling = new ProgressDialog(this, getString(R.string.cancelling));
94 | progressCancelling.setCancelable(false);
95 | progressCancelling.create();
96 | }
97 |
98 | private void initHandlePathOz() {
99 | //initialize library
100 | handlePathOz = new HandlePathOz(this, this);
101 | }
102 |
103 | ////////////////////////////////////// START ////////////////////////////////////////////
104 | private void startButton() {
105 | buttonOpen.setOnClickListener(v -> openFile());
106 | }
107 |
108 | private void startProgressBar() {
109 | progressLoading.setOnCancelListener(dialog -> {
110 | //Call progress to cancel task
111 | if (!progressCancelling.isShowing()) {
112 | progressCancelling.show();
113 | }
114 | //cancelTask
115 | handlePathOz.cancelTask();
116 | });
117 | }
118 |
119 | ////////////////////////////////////// OTHER METHODS /////////////////////////////////////
120 | private void openFile() {
121 | if (checkSelfPermission()) {
122 | Intent intent;
123 | if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
124 | intent = new Intent(ACTION_PICK, EXTERNAL_CONTENT_URI);
125 | } else {
126 | intent = new Intent(ACTION_PICK, INTERNAL_CONTENT_URI);
127 | }
128 |
129 | intent.setType("*/*");
130 | intent.setAction(Intent.ACTION_GET_CONTENT);
131 | intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
132 | intent.addCategory(Intent.CATEGORY_OPENABLE);
133 | intent.putExtra("return-data", true);
134 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
135 |
136 | startActivityForResult(intent, REQUEST_OPEN_GALLERY);
137 | }
138 | }
139 |
140 | private boolean checkSelfPermission() {
141 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
142 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
143 | return false;
144 | }
145 | return true;
146 | }
147 |
148 | ///////////////////////////// OVERRIDE METHODS //////////////////////////////////////////
149 | @Override
150 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
151 | if (requestCode == REQUEST_PERMISSION) {
152 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
153 | openFile();
154 | } else {
155 | //TODO("show Message to the user")
156 | }
157 | }
158 | }
159 |
160 | @Override
161 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
162 | super.onActivityResult(requestCode, resultCode, data);
163 | if (requestCode == REQUEST_OPEN_GALLERY && resultCode == RESULT_OK) {
164 | Uri uri = data.getData();
165 | if (uri != null) {
166 | //Update the TextView with Original Path
167 | tvOriginalPath.setText(uri.getPath());
168 | tvOriginalType.setText("Unknown");
169 | //set Uri to handle
170 | handlePathOz.getRealPath(uri);
171 | }
172 | //show Progress Loading
173 | if (!progressLoading.isShowing()) {
174 | progressLoading.show();
175 | }
176 | }
177 | }
178 |
179 | @Override
180 | public void onBackPressed() {
181 | //Cancel the task if it is working.
182 | handlePathOz.cancelTask();
183 | //Deletes temporary
184 | handlePathOz.deleteTemporaryFiles();
185 |
186 | super.onBackPressed();
187 | }
188 |
189 | @Override
190 | public void onDestroy() {
191 | handlePathOz.onDestroy();
192 | handlePathOz.deleteTemporaryFiles();
193 | super.onDestroy();
194 | }
195 |
196 | ///////////////////////////// LISTENER HANDLE PATH OZ ///////////////////////////////////
197 | @Override
198 | public void onRequestHandlePathOz(@NotNull PathOz pathOz, @Nullable Throwable tr) {
199 | //Hide Progress
200 | if (progressLoading.isShowing() || progressCancelling.isShowing()) {
201 | progressLoading.dismiss();
202 | progressCancelling.dismiss();
203 | }
204 | //Update the TextView with Real Path
205 | tvRealPath.setText(pathOz.getPath());
206 | tvRealType.setText(pathOz.getType());
207 |
208 | //Handle Exception (Optional)
209 | if (tr != null) {
210 | Toast.makeText(this, tr.getMessage(), Toast.LENGTH_SHORT).show();
211 | }
212 | }
213 | }
214 |
--------------------------------------------------------------------------------
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | orbs:
4 | changelog: onimur/github-changelog-generator@2.1.7
5 | mem: circleci/rememborb@0.0.1
6 | orb-tools: circleci/orb-tools@9.1.0
7 | tools: onimur/common-tools@0.0.2
8 |
9 | commands:
10 | # Command - Remember Environment Variables
11 | remember_var:
12 | steps:
13 | - mem/remember:
14 | env_var: DATE_FORMAT
15 | value: "%d-%m-%y"
16 | - mem/remember:
17 | env_var: OUTPUT_CHANGELOG
18 | value: CHANGELOG.md
19 | # Command - Recall Environment Variables
20 | recall_var:
21 | steps:
22 | - mem/recall:
23 | env_var: DATE_FORMAT
24 | - mem/recall:
25 | env_var: OUTPUT_CHANGELOG
26 | # Decodes Environment Variables in file
27 | generate-keystore:
28 | steps:
29 | - run:
30 | name: Decode Keystore
31 | command: |
32 | # Decode Secret keys from environment variables
33 | base64 -d \<<< $ENCODED_KEYSTORE > ${CIRCLE_WORKING_DIRECTORY/#\~/$HOME}/keystore.jks
34 | echo 'export KEYSTORE=${CIRCLE_WORKING_DIRECTORY/#\~/$HOME}/keystore.jks' >> $BASH_ENV
35 | generate-google-json:
36 | steps:
37 | - run:
38 | name: Decode Publish Google Play
39 | command: |
40 | # Decode secret file from environment variables
41 | base64 -d \<<< $ENCODED_PUBLISH_GOOGLE_PLAY > ${CIRCLE_WORKING_DIRECTORY/#\~/$HOME}/google-play.json
42 | echo 'export PUBLISH_GOOGLE=${CIRCLE_WORKING_DIRECTORY/#\~/$HOME}/google-play.json' >> $BASH_ENV
43 | jobs:
44 | # Automate versioning to library and sample app on tagged.
45 | versioning:
46 | machine: true
47 | working_directory: ~/code
48 | steps:
49 | - checkout
50 | - run:
51 | name: Generate version file
52 | command: |
53 | IFS=. read -ra SEMVER \<<< "${CIRCLE_TAG}"
54 | MAJOR=$((${SEMVER[0]}*100))
55 | MINOR=$((${SEMVER[1]}*10))
56 | PATCH=${SEMVER[2]}
57 | VERSION_CODE=$((${MAJOR} + ${MINOR} + ${PATCH}))
58 | echo "Version name: ${CIRCLE_TAG}"
59 | echo "Version code: ${VERSION_CODE}"
60 | printf -v LIB_PROP "$(<./docs/others/lib.templ.properties)" \
61 | "${CIRCLE_TAG}" "${VERSION_CODE}"
62 | echo "${LIB_PROP}" >| ./lib.properties
63 | - tools/persist-dir:
64 | paths: lib.properties
65 | # Prepare gradle build, test and release
66 | prepare:
67 | working_directory: ~/code
68 | docker:
69 | - image: circleci/android:api-29
70 | environment:
71 | JVM_OPTS: -Xmx3200m
72 | steps:
73 | # Export Env_var
74 | - remember_var
75 | - restore_cache:
76 | key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
77 | - run:
78 | name: chmod permissions
79 | command: chmod +x ./gradlew
80 | - generate-keystore
81 | - run:
82 | name: Download Dependencies
83 | command: ./gradlew androidDependencies
84 | - save_cache:
85 | paths:
86 | - ~/.gradle
87 | key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
88 | - run:
89 | name: Run Tests
90 | command: ./gradlew lint test
91 | - store_artifacts:
92 | path: app/build/reports
93 | destination: reports
94 | - store_test_results:
95 | path: app/build/test-results
96 | - run:
97 | name: Build apk
98 | command: ./gradlew assembleRelease
99 | - run:
100 | name: Copy apk
101 | command: |
102 | mkdir -p artifacts
103 | cp -r app/build/outputs/apk/release/*.apk artifacts
104 | - store_artifacts:
105 | path: artifacts
106 | destination: application
107 | - tools/persist-dir:
108 | paths: artifacts
109 |
110 | # Publish on github releases
111 | publish-github-release:
112 | docker:
113 | - image: cibuilds/github:0.13
114 | steps:
115 | - checkout
116 | - tools/attach-dir:
117 | paths: artifacts
118 | destination: ./
119 | # Get Env_Var
120 | - recall_var
121 | - run:
122 | name: Publish Release on GitHub
123 | command: |
124 | DATE=$(date +${DATE_FORMAT})
125 | TAG_WITHOUT_DOT="${CIRCLE_TAG//./}"
126 | TITLE="Handle Path Oz"
127 | URL_CHANGELOG="https://github.com/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}/blob/master/${OUTPUT_CHANGELOG}#${TAG_WITHOUT_DOT}-${DATE}"
128 | printf -v BODY "$(<./docs/others/release.templ.md)" \
129 | "${TITLE}" "${DATE}" "${CIRCLE_TAG}" "${CIRCLE_BUILD_NUM}" "${CIRCLE_BUILD_URL}" "${OUTPUT_CHANGELOG}" "${URL_CHANGELOG}"
130 | ghr \
131 | -t ${GITHUB_TOKEN} \
132 | -u ${CIRCLE_PROJECT_USERNAME} \
133 | -r ${CIRCLE_PROJECT_REPONAME} \
134 | -b "${BODY}" \
135 | -c ${CIRCLE_SHA1} \
136 | -delete ${CIRCLE_TAG} artifacts
137 | #Upload to bintray(Jcenter), nexus(Maven Central) and GithubPackages
138 | publish-to-library:
139 | working_directory: ~/code
140 | docker:
141 | - image: circleci/android:api-29
142 | environment:
143 | JVM_OPTS: -Xmx3200m
144 | steps:
145 | - checkout
146 | - tools/attach-dir:
147 | paths: lib.properties
148 | destination: ./
149 | - restore_cache:
150 | key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
151 | - generate-keystore
152 | - generate-google-json
153 | - run:
154 | name: chmod permissions
155 | command: chmod +x ./gradlew
156 | - run:
157 | name: Build apk
158 | command: ./gradlew assembleRelease
159 | - run:
160 | name: Publish to Jcenter and Maven Central
161 | command: ./gradlew clean build bintrayUpload -PdryRun=false
162 | # Command - Automate the publication of the new version of the simple app for google play.
163 | - run:
164 | name: Publish Sample Apk to Google Play
165 | command: ./gradlew publishReleaseApk
166 | # Push Changelog, Apk and new version to remote repository.
167 | push-updates-to-remote-github:
168 | machine: true
169 | steps:
170 | - checkout
171 | - tools/git-checkout
172 | - recall_var
173 | - tools/attach-dir:
174 | paths: lib.properties, ${OUTPUT_CHANGELOG}, artifacts
175 | destination: ./
176 | - tools/git-push:
177 | paths: lib.properties, ${OUTPUT_CHANGELOG}, artifacts
178 | commit-message: Auto Update Version, Changelog and Apk Release
179 | # Filters
180 | orb_tagged_filters: &orb_tagged_filters
181 | branches:
182 | ignore: /.*/
183 | tags:
184 | only: /^\d+\.\d+\.\d+$/ #for tag 1.2.3
185 |
186 | workflows:
187 | # For all branches.
188 | build:
189 | jobs:
190 | - orb-tools/lint
191 | - orb-tools/shellcheck:
192 | exclude: "SC2002,SC1073,SC1009"
193 | requires: [orb-tools/lint]
194 | - prepare:
195 | pre-steps:
196 | - checkout
197 | requires: [orb-tools/shellcheck]
198 | # for all tags
199 | tagged-publish:
200 | jobs:
201 | - versioning:
202 | filters: *orb_tagged_filters
203 | context: main-context
204 | - prepare:
205 | pre-steps:
206 | - checkout
207 | - tools/attach-dir:
208 | paths: lib.properties
209 | destination: ./
210 | filters: *orb_tagged_filters
211 | requires: [versioning]
212 | - publish-github-release:
213 | requires: [prepare]
214 | filters: *orb_tagged_filters
215 | - changelog/changelog-custom:
216 | context: main-context
217 | pre-steps:
218 | - checkout
219 | - recall_var
220 | date-format: ${DATE_FORMAT}
221 | output: ${OUTPUT_CHANGELOG}
222 | requires: [prepare]
223 | filters: *orb_tagged_filters
224 | - hold:
225 | type: approval
226 | requires:
227 | - publish-github-release
228 | - changelog/changelog-custom
229 | filters: *orb_tagged_filters
230 | - push-updates-to-remote-github:
231 | context: main-context
232 | requires: [hold]
233 | filters: *orb_tagged_filters
234 | - publish-to-library:
235 | requires: [push-updates-to-remote-github]
236 | filters: *orb_tagged_filters
237 |
--------------------------------------------------------------------------------
/handle-path-oz/src/main/java/br/com/onimur/handlepathoz/utils/PathUtils.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 29/07/20 14:25
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 29/07/20 14:21
9 | */
10 |
11 | package br.com.onimur.handlepathoz.utils
12 |
13 | import android.annotation.SuppressLint
14 | import android.content.ContentResolver
15 | import android.content.ContentUris
16 | import android.content.Context
17 | import android.net.Uri
18 | import android.os.Environment
19 | import android.provider.DocumentsContract
20 | import android.provider.MediaStore
21 | import androidx.loader.content.CursorLoader
22 | import br.com.onimur.handlepathoz.errors.EmptyGooglePhotosException
23 | import br.com.onimur.handlepathoz.errors.HandlePathOzUnknownException
24 | import br.com.onimur.handlepathoz.errors.UnknownFilePathException
25 | import br.com.onimur.handlepathoz.utils.Constants.PathUri.COLUMN_DATA
26 | import br.com.onimur.handlepathoz.utils.Constants.PathUri.COLUMN_DISPLAY_NAME
27 | import br.com.onimur.handlepathoz.utils.Constants.PathUri.FOLDER_DOWNLOAD
28 | import br.com.onimur.handlepathoz.utils.ContentUriUtils.getPathFromColumn
29 | import br.com.onimur.handlepathoz.utils.FileUtils.getSubFolders
30 | import br.com.onimur.handlepathoz.utils.SDCardUtils.getStorageDirectories
31 | import br.com.onimur.handlepathoz.utils.extension.*
32 | import java.io.File
33 |
34 | object PathUtils {
35 | /**
36 | * Get a file path from a Uri. This will get the the path for Storage Access
37 | * Framework Documents, as well as the _data field for the MediaStore and
38 | * other file-based ContentProviders.
39 | *
40 | */
41 | @SuppressLint("NewApi")
42 | @Suppress("DEPRECATION")
43 | internal fun getPathAboveKitKat(context: Context, uri: Uri): String {
44 | val contentResolver = context.contentResolver
45 | //Document Provider
46 | return when {
47 | DocumentsContract.isDocumentUri(context, uri) -> {
48 | when {
49 | uri.isExternalStorageDocument -> externalStorageDocument(context, uri)
50 | uri.isRawDownloadsDocument -> rawDownloadsDocument(contentResolver, uri)
51 | uri.isDownloadsDocument -> downloadsDocument(contentResolver, uri)
52 | uri.isMediaDocument -> mediaDocument(contentResolver, uri)
53 | else -> {
54 | logD("Another Document Provider: ${uri.authority}")
55 | return ""
56 | }
57 | }
58 | }
59 | // MediaStore (and general)
60 | uri.isMediaStore -> {
61 | val path = getPathFromColumn(contentResolver, uri, COLUMN_DATA)
62 | return if (uri.isGooglePhotosUri) googlePhotosUri(uri)
63 | ?: throw EmptyGooglePhotosException(path)
64 | else {
65 | anotherFileProvider(path)
66 | }
67 | }
68 | uri.isFile -> uri.path ?: throw UnknownFilePathException(uri.toString())
69 |
70 | else -> throw HandlePathOzUnknownException(uri.toString())
71 |
72 | }
73 | }
74 |
75 | internal fun getPathBelowKitKat(context: Context, uri: Uri): String {
76 | val projection = arrayOf(COLUMN_DATA)
77 | var path = ""
78 | val loader = CursorLoader(context, uri, projection, null, null, null)
79 | loader.loadInBackground()?.use {
80 | if (it.moveToFirst()) {
81 | val index = it.getColumnIndexOrThrow(COLUMN_DATA)
82 | path = it.getString(index)
83 | }
84 | }
85 | return path
86 | }
87 |
88 | /**
89 | * Method for external document
90 | *
91 | */
92 | @SuppressLint("NewApi")
93 | @Suppress("DEPRECATION")
94 | private fun externalStorageDocument(context: Context, uri: Uri): String {
95 | logD("File is External Storage")
96 | val docId = DocumentsContract.getDocumentId(uri)
97 | val split = docId.split(":").toTypedArray()
98 | val type = split[0]
99 | if ("primary".equals(type, ignoreCase = true)) {
100 | return if (split.size > 1) {
101 | "${Environment.getExternalStorageDirectory()}/${split[1]}"
102 | } else {
103 | "${Environment.getExternalStorageDirectory()}/"
104 | }
105 | } else {
106 | val path = "storage/${docId.replace(":", "/")}"
107 | if (File(path).exists()) {
108 | return "/$path"
109 | }
110 | val availableExternalStorage = getStorageDirectories(context)
111 | var root = ""
112 | availableExternalStorage.forEach { storage ->
113 | root = if (split[1].startsWith("/")) {
114 | "$storage${split[1]}"
115 | } else {
116 | "$storage/${split[1]}"
117 | }
118 | }
119 | return if (root.contains(type)) {
120 | path
121 | } else {
122 | if (root.startsWith("/storage/") || root.startsWith("storage/")) {
123 | root
124 | } else if (root.startsWith("/")) {
125 | "/storage$root"
126 | } else {
127 | "/storage/$root"
128 | }
129 | }
130 | }
131 | }
132 |
133 | /**
134 | * Method for rawDownloadDocument
135 | *
136 | */
137 | @Suppress("DEPRECATION")
138 | @SuppressLint("NewApi")
139 | private fun rawDownloadsDocument(contentResolver: ContentResolver, uri: Uri): String {
140 | logD("File is Raw Downloads Document")
141 | val fileName = getPathFromColumn(contentResolver, uri, COLUMN_DISPLAY_NAME)
142 | val subFolderName = getSubFolders(uri.toString())
143 | return if (fileName.isNotBlank()) {
144 | "${Environment.getExternalStorageDirectory()}/$FOLDER_DOWNLOAD/$subFolderName$fileName"
145 | } else {
146 | val id = DocumentsContract.getDocumentId(uri)
147 | val contentUri = ContentUris.withAppendedId(
148 | Uri.parse("content://downloads/public_downloads"),
149 | id.toLong()
150 | )
151 | getPathFromColumn(contentResolver, contentUri, COLUMN_DATA)
152 | }
153 | }
154 |
155 | /**
156 | * Method for downloadsDocument
157 | *
158 | */
159 | @SuppressLint("NewApi")
160 | @Suppress("DEPRECATION")
161 | private fun downloadsDocument(contentResolver: ContentResolver, uri: Uri): String {
162 | logD("File is Downloads Documents")
163 | val fileName = getPathFromColumn(contentResolver, uri, COLUMN_DISPLAY_NAME)
164 | val subFolderName = getSubFolders(uri.toString())
165 | if (fileName.isNotBlank()) {
166 | return "${Environment.getExternalStorageDirectory()}/$FOLDER_DOWNLOAD/$subFolderName$fileName"
167 | }
168 | var id = DocumentsContract.getDocumentId(uri)
169 | if (id.startsWith("raw:")) {
170 | id = id.replaceFirst("raw:".toRegex(), "")
171 | val file = File(id)
172 | if (file.exists()) return id
173 | } else if (id.startsWith("raw%3A%2F")) {
174 | id = id.replaceFirst("raw%3A%2F".toRegex(), "")
175 | val file = File(id)
176 | if (file.exists()) return id
177 | }
178 | val contentUri = ContentUris.withAppendedId(
179 | Uri.parse("content://downloads/public_downloads"),
180 | id.toLong()
181 | )
182 | return getPathFromColumn(contentResolver, contentUri, COLUMN_DATA)
183 | }
184 |
185 | /**
186 | * Method for MediaDocument
187 | *
188 | */
189 | @SuppressLint("NewApi")
190 | private fun mediaDocument(contentResolver: ContentResolver, uri: Uri): String {
191 | logD("File is Media Document")
192 | val docId = DocumentsContract.getDocumentId(uri)
193 | val split: Array = docId.split(":").toTypedArray()
194 | val contentUri: Uri =
195 | when (split[0]) {
196 | "image" -> MediaStore.Images.Media.EXTERNAL_CONTENT_URI
197 | "video" -> MediaStore.Video.Media.EXTERNAL_CONTENT_URI
198 | "audio" -> MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
199 | //Todo test
200 | else -> MediaStore.Files.getContentUri(docId)
201 | }
202 | val selection = "_id=?"
203 | val selectionArgs = arrayOf(split[1])
204 | return getPathFromColumn(
205 | contentResolver,
206 | contentUri,
207 | COLUMN_DATA,
208 | selection,
209 | selectionArgs
210 | )
211 | }
212 |
213 | /**
214 | * Method for googlePhotos
215 | *
216 | */
217 | private fun googlePhotosUri(uri: Uri): String? {
218 | // Return the remote address
219 | logD("File is Google Photos")
220 | return uri.lastPathSegment
221 | }
222 |
223 | /**
224 | *
225 | * Different fileprovider
226 | */
227 | private fun anotherFileProvider(path: String): String {
228 | if (path.isBlank()) {
229 | logD("Unknown File Provider")
230 | } else {
231 | logD("Another File Provider")
232 | }
233 | return path
234 | }
235 | }
236 |
--------------------------------------------------------------------------------
/app/src/main/java/br/com/onimur/sample/handlepathoz/kotlin/MultipleUriActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 29/07/20 17:45
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 29/07/20 17:08
9 | */
10 |
11 | package br.com.onimur.sample.handlepathoz.kotlin
12 |
13 | import android.Manifest.permission.WRITE_EXTERNAL_STORAGE
14 | import android.app.Activity
15 | import android.content.Intent
16 | import android.content.Intent.ACTION_PICK
17 | import android.content.pm.PackageManager.PERMISSION_GRANTED
18 | import android.net.Uri
19 | import android.os.Bundle
20 | import android.os.Environment
21 | import android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI
22 | import android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI
23 | import android.widget.Button
24 | import android.widget.Toast
25 | import androidx.appcompat.app.AppCompatActivity
26 | import androidx.core.app.ActivityCompat
27 | import androidx.core.content.ContextCompat
28 | import androidx.recyclerview.widget.LinearLayoutManager
29 | import androidx.recyclerview.widget.RecyclerView
30 | import br.com.comino.sample.handlepathoz.R
31 | import br.com.onimur.handlepathoz.HandlePathOz
32 | import br.com.onimur.handlepathoz.HandlePathOzListener
33 | import br.com.onimur.handlepathoz.model.PathOz
34 | import br.com.onimur.handlepathoz.utils.extension.getListUri
35 | import br.com.onimur.sample.handlepathoz.kotlin.adapter.RealPathAdapter
36 | import br.com.onimur.sample.handlepathoz.kotlin.model.PathModel
37 | import kotlinx.coroutines.FlowPreview
38 |
39 | class MultipleUriActivity : AppCompatActivity(R.layout.activity_multiple_uri),
40 | HandlePathOzListener.MultipleUri {
41 |
42 | companion object {
43 | const val REQUEST_PERMISSION = 123
44 | const val REQUEST_OPEN_GALLERY = 1111
45 | }
46 |
47 | private var listUri = emptyList()
48 | private lateinit var buttonOpen: Button
49 | private lateinit var rvOriginal: RecyclerView
50 | private lateinit var rvReal: RecyclerView
51 | private lateinit var originalAdapter: RealPathAdapter
52 | private lateinit var realAdapter: RealPathAdapter
53 | private lateinit var progressLoading: ProgressDialog
54 | private lateinit var progressCancelling: ProgressDialog
55 | private lateinit var handlePathOz: HandlePathOz
56 |
57 | override fun onCreate(savedInstanceState: Bundle?) {
58 | super.onCreate(savedInstanceState)
59 | //
60 | init()
61 | startAction()
62 | //
63 | }
64 |
65 | private fun init() {
66 | initButton()
67 | initRecyclerView()
68 | initAdapter()
69 | initProgressBar()
70 | initHandlePathOz()
71 |
72 | }
73 |
74 | private fun startAction() {
75 | startButton()
76 | startRecyclerView()
77 | startProgressBar()
78 | }
79 |
80 | ////////////////////////////////////// INIT /////////////////////////////////////////////
81 | private fun initButton() {
82 | buttonOpen = findViewById(R.id.btn_open)
83 | }
84 |
85 | private fun initRecyclerView() {
86 | rvOriginal = findViewById(R.id.lv_original)
87 | rvReal = findViewById(R.id.lv_real)
88 | }
89 |
90 | private fun initAdapter() {
91 | originalAdapter = RealPathAdapter(ArrayList())
92 | realAdapter = RealPathAdapter(ArrayList())
93 | }
94 |
95 | private fun initProgressBar() {
96 | progressLoading = ProgressDialog(this, getString(R.string.validating)).apply {
97 | setCancelable(true)
98 | create()
99 | }
100 |
101 | progressCancelling = ProgressDialog(this, getString(R.string.cancelling)).apply {
102 | setCancelable(false)
103 | create()
104 | }
105 | }
106 |
107 | private fun initHandlePathOz() {
108 | //initialize library
109 | handlePathOz = HandlePathOz(this, this)
110 | }
111 |
112 | ////////////////////////////////////// START ////////////////////////////////////////////
113 | private fun startButton() {
114 | buttonOpen.setOnClickListener { openFile() }
115 | }
116 |
117 | private fun startRecyclerView() {
118 | rvOriginal.apply {
119 | // use this setting to improve performance if you know that changes
120 | // in content do not change the layout size of the RecyclerView
121 | setHasFixedSize(true)
122 | // use a linear layout manager
123 | layoutManager = LinearLayoutManager(context)
124 | // specify an viewAdapter (see also next example)
125 | adapter = originalAdapter
126 | }
127 |
128 | rvReal.apply {
129 | setHasFixedSize(true)
130 | layoutManager = LinearLayoutManager(context)
131 | adapter = realAdapter
132 | }
133 | }
134 |
135 | private fun startProgressBar() {
136 | progressLoading.setOnCancelListener {
137 | //Call progress to cancel task
138 | if (!progressCancelling.isShowing) {
139 | progressCancelling.show()
140 | }
141 | //cancelTask
142 | handlePathOz.cancelTask()
143 |
144 | }
145 | }
146 |
147 | ////////////////////////////////////// OTHER METHODS /////////////////////////////////////
148 | private fun openFile() {
149 | if (checkSelfPermission()) {
150 | val intent =
151 | if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
152 | Intent(ACTION_PICK, EXTERNAL_CONTENT_URI)
153 | } else {
154 | Intent(ACTION_PICK, INTERNAL_CONTENT_URI)
155 | }
156 |
157 | intent.apply {
158 | type = "*/*"
159 | action = Intent.ACTION_GET_CONTENT
160 | action = Intent.ACTION_OPEN_DOCUMENT
161 | addCategory(Intent.CATEGORY_OPENABLE)
162 | putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
163 | putExtra("return-data", true)
164 | addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
165 | }
166 | startActivityForResult(intent, REQUEST_OPEN_GALLERY)
167 | }
168 | }
169 |
170 | private fun checkSelfPermission(): Boolean {
171 | if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE)
172 | != PERMISSION_GRANTED
173 | ) {
174 | ActivityCompat.requestPermissions(
175 | this,
176 | arrayOf(WRITE_EXTERNAL_STORAGE),
177 | REQUEST_PERMISSION
178 | )
179 | return false
180 | }
181 | return true
182 | }
183 |
184 | ///////////////////////////// OVERRIDE METHODS //////////////////////////////////////////
185 | override fun onRequestPermissionsResult(
186 | requestCode: Int,
187 | permissions: Array,
188 | grantResults: IntArray
189 | ) {
190 | if (requestCode == REQUEST_PERMISSION) {
191 | if (grantResults[0] == PERMISSION_GRANTED) {
192 | openFile()
193 | } else {
194 | TODO("show Message to the user")
195 | }
196 | }
197 | }
198 |
199 | @FlowPreview
200 | override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
201 | super.onActivityResult(requestCode, resultCode, data)
202 | if ((requestCode == REQUEST_OPEN_GALLERY) and (resultCode == Activity.RESULT_OK)) {
203 | //This extension retrieves the path of all selected files without treatment.
204 | listUri = data.getListUri()
205 | //Update the adapter
206 |
207 | originalAdapter.updateListChanged(listUri.map {
208 | PathModel(
209 | PathOz(
210 | "unknown",
211 | it.path.toString()
212 | )
213 | )
214 | })
215 |
216 | //set list of the Uri to handle
217 | //in concurrency use:
218 | // 1 -> for tasks sequentially
219 | //greater than 1 -> for the number of tasks you want to perform in parallel.
220 | //Nothing -> for parallel tasks - by default the value is 10
221 | handlePathOz.getListRealPath(listUri)
222 | // handlePathOz.getListRealPath(listUri, 1)
223 | //show Progress Loading
224 | if (!progressLoading.isShowing) {
225 | progressLoading.show()
226 | }
227 | }
228 | }
229 |
230 | override fun onBackPressed() {
231 | with(handlePathOz) {
232 | //Cancel the task if it is working.
233 | cancelTask()
234 | //Deletes temporary files
235 | deleteTemporaryFiles()
236 | }
237 | super.onBackPressed()
238 | }
239 |
240 | override fun onDestroy() {
241 | with(handlePathOz) {
242 | onDestroy()
243 | deleteTemporaryFiles()
244 | }
245 | super.onDestroy()
246 | }
247 |
248 |
249 | ///////////////////////////// LISTENER HANDLE PATH OZ ///////////////////////////////////
250 | override fun onRequestHandlePathOz(listPathOz: List, tr: Throwable?) {
251 | //Hide Progress
252 | if (progressLoading.isShowing or progressCancelling.isShowing) {
253 | progressLoading.dismiss()
254 | progressCancelling.dismiss()
255 | }
256 | //Update the adapter
257 | realAdapter.updateListChanged(listPathOz.map { pathOz ->
258 | PathModel(pathOz)
259 | })
260 |
261 | //Handle Exception (Optional)
262 | tr?.let {
263 | Toast.makeText(this, "${it.message}", Toast.LENGTH_SHORT).show()
264 | }
265 | }
266 |
267 | //This method is Optional
268 | override fun onLoading(currentUri: Int) {
269 | progressLoading.currentLoad = "${currentUri}/${listUri.size}"
270 | }
271 | }
272 |
--------------------------------------------------------------------------------
/app/src/main/java/br/com/onimur/sample/handlepathoz/java/MultipleUriActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Created by Murillo Comino on 29/07/20 17:45
3 | * Github: github.com/onimur
4 | * StackOverFlow: pt.stackoverflow.com/users/128573
5 | * Email: murillo_comino@hotmail.com
6 | *
7 | * Copyright (c) 2020.
8 | * Last modified 29/07/20 17:08
9 | */
10 |
11 | package br.com.onimur.sample.handlepathoz.java;
12 |
13 | import android.Manifest;
14 | import android.content.Intent;
15 | import android.content.pm.PackageManager;
16 | import android.net.Uri;
17 | import android.os.Bundle;
18 | import android.os.Environment;
19 | import android.widget.Button;
20 | import android.widget.Toast;
21 |
22 | import androidx.annotation.NonNull;
23 | import androidx.appcompat.app.AppCompatActivity;
24 | import androidx.core.app.ActivityCompat;
25 | import androidx.core.content.ContextCompat;
26 | import androidx.recyclerview.widget.LinearLayoutManager;
27 | import androidx.recyclerview.widget.RecyclerView;
28 |
29 | import org.jetbrains.annotations.NotNull;
30 | import org.jetbrains.annotations.Nullable;
31 |
32 | import java.util.ArrayList;
33 | import java.util.List;
34 | import java.util.Objects;
35 |
36 | import br.com.comino.sample.handlepathoz.R;
37 | import br.com.onimur.handlepathoz.HandlePathOz;
38 | import br.com.onimur.handlepathoz.HandlePathOzListener;
39 | import br.com.onimur.handlepathoz.model.PathOz;
40 | import br.com.onimur.sample.handlepathoz.kotlin.ProgressDialog;
41 | import br.com.onimur.sample.handlepathoz.kotlin.adapter.RealPathAdapter;
42 | import br.com.onimur.sample.handlepathoz.kotlin.model.PathModel;
43 |
44 | import static android.content.Intent.ACTION_PICK;
45 | import static android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
46 | import static android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI;
47 | import static br.com.onimur.handlepathoz.utils.extension.PathsKt.getListUri;
48 |
49 | public class MultipleUriActivity extends AppCompatActivity implements HandlePathOzListener.MultipleUri {
50 |
51 | private static final int REQUEST_PERMISSION = 123;
52 | private static final int REQUEST_OPEN_GALLERY = 1111;
53 |
54 | private List listUri;
55 | private Button buttonOpen;
56 | private RecyclerView rvOriginal;
57 | private RecyclerView rvReal;
58 | private RealPathAdapter originalAdapter;
59 | private RealPathAdapter realAdapter;
60 | private ProgressDialog progressLoading;
61 | private ProgressDialog progressCancelling;
62 | private HandlePathOz handlePathOz;
63 |
64 | @Override
65 | protected void onCreate(Bundle savedInstanceState) {
66 | super.onCreate(savedInstanceState);
67 | setContentView(R.layout.activity_multiple_uri);
68 |
69 | init();
70 | startAction();
71 | }
72 |
73 | private void init() {
74 | initButton();
75 | initRecyclerView();
76 | initAdapter();
77 | initProgressBar();
78 | initHandlePathOz();
79 | }
80 |
81 | private void startAction() {
82 | startButton();
83 | startRecyclerView();
84 | startProgressBar();
85 | }
86 |
87 | ////////////////////////////////////// INIT /////////////////////////////////////////////
88 | private void initButton() {
89 | buttonOpen = findViewById(R.id.btn_open);
90 | }
91 |
92 | private void initRecyclerView() {
93 | rvOriginal = findViewById(R.id.lv_original);
94 | rvReal = findViewById(R.id.lv_real);
95 | }
96 |
97 | private void initAdapter() {
98 | originalAdapter = new RealPathAdapter(new ArrayList<>());
99 | realAdapter = new RealPathAdapter(new ArrayList<>());
100 | }
101 |
102 | private void initProgressBar() {
103 | progressLoading = new ProgressDialog(this, getString(R.string.validating));
104 | progressLoading.setCancelable(true);
105 | progressLoading.create();
106 |
107 | progressCancelling = new ProgressDialog(this, getString(R.string.cancelling));
108 | progressCancelling.setCancelable(false);
109 | progressCancelling.create();
110 | }
111 |
112 | private void initHandlePathOz() {
113 | //initialize library
114 | handlePathOz = new HandlePathOz(this, this);
115 | }
116 |
117 | ////////////////////////////////////// START ////////////////////////////////////////////
118 | private void startButton() {
119 | buttonOpen.setOnClickListener(v -> openFile());
120 | }
121 |
122 | private void startRecyclerView() {
123 | // use this setting to improve performance if you know that changes
124 | // in content do not change the layout size of the RecyclerView
125 | rvOriginal.setHasFixedSize(true);
126 | // use a linear layout manager
127 | rvOriginal.setLayoutManager(new LinearLayoutManager(this));
128 | // specify an viewAdapter (see also next example)
129 | rvOriginal.setAdapter(originalAdapter);
130 | //
131 | //
132 | rvReal.setHasFixedSize(true);
133 | rvReal.setLayoutManager(new LinearLayoutManager(this));
134 | rvReal.setAdapter(realAdapter);
135 | }
136 |
137 | private void startProgressBar() {
138 | progressLoading.setOnCancelListener(dialog -> {
139 | //Call progress to cancel task
140 | if (!progressCancelling.isShowing()) {
141 | progressCancelling.show();
142 | }
143 | //cancelTask
144 | handlePathOz.cancelTask();
145 | });
146 | }
147 |
148 | ////////////////////////////////////// OTHER METHODS /////////////////////////////////////
149 | private void openFile() {
150 | if (checkSelfPermission()) {
151 | Intent intent;
152 | if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
153 | intent = new Intent(ACTION_PICK, EXTERNAL_CONTENT_URI);
154 | } else {
155 | intent = new Intent(ACTION_PICK, INTERNAL_CONTENT_URI);
156 | }
157 |
158 | intent.setType("*/*");
159 | intent.setAction(Intent.ACTION_GET_CONTENT);
160 | intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
161 | intent.addCategory(Intent.CATEGORY_OPENABLE);
162 | intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
163 | intent.putExtra("return-data", true);
164 | intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
165 |
166 | startActivityForResult(intent, REQUEST_OPEN_GALLERY);
167 | }
168 | }
169 |
170 | private boolean checkSelfPermission() {
171 | if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
172 | ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION);
173 | return false;
174 | }
175 | return true;
176 | }
177 |
178 | ///////////////////////////// OVERRIDE METHODS //////////////////////////////////////////
179 | @Override
180 | public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
181 | if (requestCode == REQUEST_PERMISSION) {
182 | if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
183 | openFile();
184 | } else {
185 | //TODO("show Message to the user")
186 | }
187 | }
188 | }
189 |
190 | @Override
191 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
192 | super.onActivityResult(requestCode, resultCode, data);
193 | if (requestCode == REQUEST_OPEN_GALLERY && resultCode == RESULT_OK) {
194 | //This extension retrieves the path of all selected files without treatment.
195 | listUri = getListUri(data);
196 | //Update the adapter
197 | List listPath = new ArrayList<>();
198 | for (int i = 0; i < listUri.size(); i++) {
199 | String path = listUri.get(i).getPath();
200 | PathOz pathOz = new PathOz("unknown", Objects.requireNonNull(path));
201 | PathModel pathModel = new PathModel(pathOz);
202 | listPath.add(pathModel);
203 | }
204 | originalAdapter.updateListChanged(listPath);
205 |
206 | //set list of the Uri to handle
207 | //in concurrency use:
208 | // 1 -> for tasks sequentially
209 | //greater than 1 -> for the number of tasks you want to perform in parallel.
210 | //Nothing -> for parallel tasks - by default the value is 10
211 | handlePathOz.getListRealPath(listUri);
212 | // handlePathOz.getListRealPath(listUri, 1)
213 | //show Progress Loading
214 | if (!progressLoading.isShowing()) {
215 | progressLoading.show();
216 | }
217 | }
218 | }
219 |
220 | @Override
221 | public void onBackPressed() {
222 | //Cancel the task if it is working.
223 | handlePathOz.cancelTask();
224 | //Deletes temporary
225 | handlePathOz.deleteTemporaryFiles();
226 |
227 | super.onBackPressed();
228 | }
229 |
230 | @Override
231 | public void onDestroy() {
232 | handlePathOz.onDestroy();
233 | handlePathOz.deleteTemporaryFiles();
234 | super.onDestroy();
235 | }
236 |
237 | ///////////////////////////// LISTENER HANDLE PATH OZ ///////////////////////////////////
238 | @Override
239 | public void onRequestHandlePathOz(@NotNull List listPath, @Nullable Throwable tr) {
240 | //Hide Progress
241 | if (progressLoading.isShowing() || progressCancelling.isShowing()) {
242 | progressLoading.dismiss();
243 | progressCancelling.dismiss();
244 | }
245 |
246 | //Update the adapter
247 | List listPathModel = new ArrayList<>();
248 | for (int i = 0; i < listPath.size(); i++) {
249 | PathOz pathOz = listPath.get(i);
250 | PathModel pathModel = new PathModel(pathOz);
251 | listPathModel.add(pathModel);
252 | }
253 | realAdapter.updateListChanged(listPathModel);
254 |
255 | //Handle Exception (Optional)
256 | if (tr != null) {
257 | Toast.makeText(this, tr.getMessage(), Toast.LENGTH_SHORT).show();
258 | }
259 | }
260 |
261 | //This method is Optional
262 | @Override
263 | public void onLoading(int currentUri) {
264 | progressLoading.setCurrentLoad(currentUri + "/" + listUri.size());
265 | }
266 | }
267 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright (C) 2020 HandlePathOz
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------