├── .gitignore ├── LICENSE ├── README.md ├── app ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── org │ │ └── shagi │ │ └── filepickersample │ │ ├── App.kt │ │ ├── CustomPicker.kt │ │ ├── MainActivity.kt │ │ └── SampleActivity.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ ├── activity_main.xml │ ├── activity_sample.xml │ └── file_picker_layout.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.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 │ ├── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml │ └── xml │ └── provider_paths.xml ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── library ├── .gitignore ├── build.gradle └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── org │ │ └── shagi │ │ └── filepicker │ │ ├── CacheController.kt │ │ ├── CustomActionItem.kt │ │ ├── ExtFile.kt │ │ ├── FilePicker.kt │ │ ├── FilePickerDialog.kt │ │ ├── FilePickerFragment.kt │ │ ├── FilePickerSettings.kt │ │ ├── FilePickerUtils.kt │ │ ├── FileType.kt │ │ ├── IntentResolver.kt │ │ └── SaveFileAsyncTask.kt │ └── res │ ├── drawable │ ├── file_picker_ic_camera.xml │ ├── file_picker_ic_file_upload.xml │ ├── file_picker_ic_folder.xml │ └── file_picker_ic_image.xml │ ├── layout │ ├── file_picker_action_layout.xml │ └── file_picker_dialog_layout.xml │ └── values │ ├── dimens.xml │ └── strings.xml ├── screenshot_1.jpg ├── screenshot_2.jpg ├── screenshot_3.jpg └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | proguard-rules.pro 10 | app/build -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AsyncFilePicker 2 | 3 | ###### !!! Some features may work unstable, make sure you have tested it. Thanks. 4 | 5 | **Feel free to fork or issue pull requests on github. Issues can be reported on the github issue tracker.** 6 | 7 | File picker allows you to take photo and files from camera\gallery\filesystem 8 | and also you can add up to 3 own custom actions. 9 | 10 | Picker will ask for camera and gallery permission on android version 6.0 or above. 11 | 12 | ![screenshot](screenshot_1.jpg) 13 | 14 | # Install 15 | To add this library to your project, you must add the JitPack repo to your root build.gradle file... 16 | 17 | ```groovy 18 | allprojects { 19 | repositories { 20 | ... 21 | jcenter() 22 | } 23 | } 24 | ``` 25 | 26 | Then include this in your dependencies block 27 | 28 | ```groovy 29 | implementation 'org.shagi:filepicker:0.4' 30 | ``` 31 | 32 | # Usage 33 | 34 | 1. Add permissions and provider block to your's AndroidManifest.xml 35 | ```xml 36 | 37 | 38 | ``` 39 | ```xml 40 | 45 | 48 | 49 | ``` 50 | 2. Create file provider_paths.xml 51 | ```xml 52 | 53 | 54 | 55 | 56 | ``` 57 | 3. For simple use instantiate FilePickerFragment and in OnClick method pass FilePickerDialog into fragment. 58 | 59 | *ExtFile* - wrapper object for File object with additional data such as (baseUri, mimeType, fileName) 60 | 61 | Note: By default cache is not used and each time you take photo or file it will have same name, 62 | so Picasso or other image loading libraries can cache the **first image** by filename. 63 | To avoid that you can to save received file by yourself or use cache in FilePickerFragment or use memoryPolicy(MemoryPolicy.NO_CACHE) in Picasso. 64 | 65 | ```kotlin 66 | val pickerFragment = FilePickerFragment.getFragment(supportFragmentManager, useCache) 67 | view.setOnClickListener { 68 | pickerFragment.use(FilePickerDialog.newInstance()) 69 | pickerFragment.setOnLoadingListener(object : FilePicker.OnLoadingListener { 70 | override fun onLoadingStart(key: Long) { 71 | imageView.setImageResource(R.color.colorAccent) 72 | textView.text = "loading" 73 | } 74 | 75 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 76 | textView.text = file.toString() 77 | 78 | Picasso.get() 79 | .load(file.file) 80 | .memoryPolicy(MemoryPolicy.NO_CACHE) 81 | .into(imageView) 82 | } 83 | 84 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 85 | textView.text = throwable.message 86 | } 87 | 88 | }) 89 | pickerFragment.show() 90 | } 91 | 92 | ``` 93 | 94 | ### Available functions 95 | 96 | ##### Customisation 97 | 98 | You can customise picker dialog with own layout. Override onCreateView method and pass there layout with same view ids as in base FilePickerDialog layout - file_picker_dialog_layout 99 | ```kotlin 100 | class CustomPicker : FilePickerDialog() { 101 | 102 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = 103 | inflater.inflate(R.layout.file_picker_layout, container, false) 104 | 105 | } 106 | ``` 107 | 108 | ![screenshot](screenshot_2.jpg) 109 | 110 | ##### Cache and Settings 111 | 112 | **By default each file and photo returned overrides one temp file, and you have to save this file by yourself.** 113 | 114 | If you want to upload multiple at one time you can turn cache on by passing true as second param to FilePickerFragment.getFragment(fm,useCache). 115 | 116 | You can setup maxCacheSize, maxFileSize, maxWidth, maxHeight use FilePickerFragment.setup(FilePickerSettings) method 117 | 118 | ```kotlin 119 | val pickerFragment = FilePickerFragment.getFragment(supportFragmentManager, true).apply { 120 | use(initFilePickerDialog()) 121 | setup(settings) 122 | } 123 | ``` 124 | 125 | ```kotlin 126 | private fun initFilePickerDialog() = 127 | if (useCustomLayout) { // to user Custom Picker 128 | CustomPicker() 129 | } else { 130 | FilePickerDialog.newInstance() 131 | }.apply { 132 | showCamera = !cameraDisabled // to show camera picker row 133 | showGallery = !galleryDisabled // to show gallery picker row 134 | showFileSystem = !filesDisabled // to show file system picker row 135 | 136 | if (!customActionDisabled) { // to use custom action 137 | addCustomAction(CustomActionItem(R.drawable.file_picker_ic_folder, 138 | R.string.fpd_load_from_medical_note_documents, 139 | View.OnClickListener { 140 | Toast.makeText(context, "Custom action clicked", Toast.LENGTH_SHORT).show() 141 | }) 142 | ) 143 | } 144 | } 145 | ``` 146 | 147 | ![screenshot](screenshot_3.jpg) 148 | 149 | # License 150 | 151 | 152 | Copyright 2018 shagiz 153 | 154 | Licensed under the Apache License, Version 2.0 (the "License"); 155 | you may not use this file except in compliance with the License. 156 | You may obtain a copy of the License at 157 | 158 | http://www.apache.org/licenses/LICENSE-2.0 159 | 160 | Unless required by applicable law or agreed to in writing, software 161 | distributed under the License is distributed on an "AS IS" BASIS, 162 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 163 | See the License for the specific language governing permissions and 164 | limitations under the License. 165 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | apply plugin: 'kotlin-android' 4 | 5 | apply plugin: 'kotlin-android-extensions' 6 | 7 | android { 8 | compileSdkVersion 27 9 | defaultConfig { 10 | applicationId "org.shagi.filepicker" 11 | minSdkVersion 17 12 | targetSdkVersion 27 13 | versionCode 2 14 | versionName "1.1" 15 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 16 | vectorDrawables.useSupportLibrary = true 17 | } 18 | buildTypes { 19 | release { 20 | minifyEnabled false 21 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 22 | } 23 | } 24 | } 25 | 26 | dependencies { 27 | implementation fileTree(dir: 'libs', include: ['*.jar']) 28 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 29 | 30 | 31 | implementation 'com.android.support.constraint:constraint-layout:1.1.1' 32 | 33 | implementation 'com.jakewharton.timber:timber:4.7.0' 34 | implementation 'com.squareup.picasso:picasso:2.71828' 35 | implementation 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0' 36 | 37 | implementation 'com.android.support:appcompat-v7:27.1.1' 38 | implementation "com.android.support:exifinterface:27.1.1" 39 | implementation "com.android.support:design:27.1.1" 40 | implementation "com.android.support:support-v4:27.1.1" 41 | 42 | // implementation 'org.shagi:filepicker:0.2' 43 | implementation project(":library") 44 | } 45 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 39 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /app/src/main/java/org/shagi/filepickersample/App.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepickersample 2 | 3 | import android.app.Application 4 | 5 | import timber.log.Timber 6 | 7 | class App : Application() { 8 | override fun onCreate() { 9 | super.onCreate() 10 | Timber.plant(Timber.DebugTree()) 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/java/org/shagi/filepickersample/CustomPicker.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepickersample 2 | 3 | import android.os.Bundle 4 | import android.view.LayoutInflater 5 | import android.view.View 6 | import android.view.ViewGroup 7 | import org.shagi.filepicker.FilePickerDialog 8 | 9 | class CustomPicker : FilePickerDialog() { 10 | 11 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = 12 | inflater.inflate(R.layout.file_picker_layout, container, false) 13 | 14 | } 15 | -------------------------------------------------------------------------------- /app/src/main/java/org/shagi/filepickersample/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepickersample 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import android.view.View 6 | import android.widget.ImageView 7 | import android.widget.Toast 8 | import com.squareup.picasso.Picasso 9 | import kotlinx.android.synthetic.main.activity_main.* 10 | import org.shagi.filepicker.* 11 | import timber.log.Timber 12 | 13 | class MainActivity : AppCompatActivity(), FilePicker.OnLoadingListener { 14 | private var keys: MutableList = ArrayList() 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | Timber.d("DebugTag, onCreate $this") 19 | 20 | setContentView(R.layout.activity_main) 21 | val listener: View.OnClickListener 22 | 23 | val filePickerDialog = FilePickerDialog.newInstance().apply { 24 | multipleSelect = true 25 | addCustomAction( 26 | CustomActionItem(R.drawable.file_picker_ic_folder, 27 | R.string.fpd_load_from_medical_note_documents, 28 | View.OnClickListener { 29 | Toast.makeText(context, "1 $context", Toast.LENGTH_SHORT).show() 30 | }) 31 | ) 32 | addCustomAction( 33 | CustomActionItem(R.drawable.file_picker_ic_folder, 34 | R.string.fpd_load_from_medical_note_documents, 35 | View.OnClickListener { 36 | Toast.makeText(context, "2 $context", Toast.LENGTH_SHORT).show() 37 | }) 38 | ) 39 | } 40 | 41 | if (savedInstanceState == null) { 42 | listener = View.OnClickListener { 43 | FilePickerFragment.getFragment(supportFragmentManager, false).apply { 44 | setOnLoadingListener(this@MainActivity) 45 | use(filePickerDialog) 46 | }.show() 47 | } 48 | } else { 49 | keys = savedInstanceState.getLongArray(ARG_KEYS).toMutableList() 50 | val fragment = FilePickerFragment.getFragment(supportFragmentManager).apply { 51 | setOnLoadingListener(this@MainActivity) 52 | use(filePickerDialog) 53 | } 54 | listener = View.OnClickListener { fragment.show() } 55 | } 56 | 57 | image_1.setOnClickListener(listener) 58 | image_2.setOnClickListener(listener) 59 | image_3.setOnClickListener(listener) 60 | image_4.setOnClickListener(listener) 61 | 62 | Timber.d("listener ${image_1.hasOnClickListeners()}") 63 | } 64 | 65 | override fun onSaveInstanceState(outState: Bundle) { 66 | super.onSaveInstanceState(outState) 67 | outState.putLongArray(ARG_KEYS, keys.toLongArray()) 68 | } 69 | 70 | override fun onLoadingStart(key: Long) { 71 | progress.visibility = View.VISIBLE 72 | keys.add(key) 73 | Timber.d("DebugTag, main onLoadingStart $this with key $key") 74 | } 75 | 76 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 77 | progress.visibility = View.GONE 78 | 79 | Timber.d("DebugTag, onLoadingSuccess $key" + 80 | "\n ${file.file}" + 81 | "\n ${file.baseUri}" + 82 | "\n ${file.name}" + 83 | "\n ${file.extension}" + 84 | "\n ${file.mimeType}") 85 | 86 | val imageView: ImageView = when (keys.size) { 87 | 0 -> image_1 88 | 1 -> image_2 89 | 2 -> image_3 90 | 3 -> image_4 91 | else -> image_1 92 | } 93 | 94 | keys.remove(key) 95 | 96 | Picasso.get() 97 | .load(file.file) 98 | .into(imageView) 99 | 100 | Timber.d("DebugTag, main onLoadingSuccess $this with key $key") 101 | } 102 | 103 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 104 | progress.visibility = View.GONE 105 | Timber.d("DebugTag, main onLoadingFailure $this with key $key") 106 | Timber.e(throwable) 107 | } 108 | 109 | companion object { 110 | const val ARG_KEYS = "arg_keys" 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /app/src/main/java/org/shagi/filepickersample/SampleActivity.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepickersample 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import android.view.View 6 | import android.widget.Toast 7 | import com.squareup.picasso.MemoryPolicy 8 | import com.squareup.picasso.Picasso 9 | import kotlinx.android.synthetic.main.activity_sample.* 10 | import org.shagi.filepicker.* 11 | 12 | class SampleActivity : AppCompatActivity() { 13 | private var useCache = false 14 | private var multipleSelect = false 15 | private var cameraDisabled = false 16 | private var galleryDisabled = false 17 | private var filesDisabled = false 18 | private var customActionDisabled = false 19 | private var useCustomLayout = false 20 | 21 | override fun onCreate(savedInstanceState: Bundle?) { 22 | super.onCreate(savedInstanceState) 23 | setContentView(R.layout.activity_sample) 24 | 25 | val pickerFragment = FilePickerFragment.getFragment(supportFragmentManager) 26 | 27 | sample_file_container_1.setOnClickListener { 28 | pickerFragment.use(initFilePickerDialog()) 29 | pickerFragment.setOnLoadingListener(object : FilePicker.OnLoadingListener { 30 | override fun onLoadingStart(key: Long) { 31 | sample_file_container_1_iv.setImageResource(R.color.colorAccent) 32 | sample_file_container_1_info.text = "loading" 33 | } 34 | 35 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 36 | sample_file_container_1_info.text = file.toString() 37 | 38 | Picasso.get() 39 | .load(file.file) 40 | .memoryPolicy(MemoryPolicy.NO_CACHE) 41 | .into(sample_file_container_1_iv) 42 | } 43 | 44 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 45 | sample_file_container_1_info.text = throwable.message 46 | } 47 | 48 | }) 49 | pickerFragment.show() 50 | } 51 | 52 | sample_file_container_2.setOnClickListener { 53 | pickerFragment.use(initFilePickerDialog()) 54 | pickerFragment.setOnLoadingListener(object : FilePicker.OnLoadingListener { 55 | override fun onLoadingStart(key: Long) { 56 | sample_file_container_2_iv.setImageResource(R.color.colorAccent) 57 | sample_file_container_2_info.text = "loading" 58 | } 59 | 60 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 61 | sample_file_container_2_info.text = file.toString() 62 | 63 | Picasso.get() 64 | .load(file.file) 65 | .memoryPolicy(MemoryPolicy.NO_CACHE) 66 | .into(sample_file_container_2_iv) 67 | } 68 | 69 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 70 | sample_file_container_2_info.text = throwable.message 71 | } 72 | 73 | }) 74 | pickerFragment.show() 75 | } 76 | 77 | sample_file_container_3.setOnClickListener { 78 | pickerFragment.use(initFilePickerDialog()) 79 | pickerFragment.setOnLoadingListener(object : FilePicker.OnLoadingListener { 80 | override fun onLoadingStart(key: Long) { 81 | sample_file_container_3_iv.setImageResource(R.color.colorAccent) 82 | sample_file_container_3_info.text = "loading" 83 | } 84 | 85 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 86 | sample_file_container_3_info.text = file.toString() 87 | 88 | Picasso.get() 89 | .load(file.file) 90 | .into(sample_file_container_3_iv) 91 | } 92 | 93 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 94 | sample_file_container_3_info.text = throwable.message 95 | } 96 | 97 | }) 98 | pickerFragment.show() 99 | } 100 | 101 | sample_file_container_4.setOnClickListener { 102 | pickerFragment.use(initFilePickerDialog()) 103 | pickerFragment.setOnLoadingListener(object : FilePicker.OnLoadingListener { 104 | override fun onLoadingStart(key: Long) { 105 | sample_file_container_4_iv.setImageResource(R.color.colorAccent) 106 | sample_file_container_4_info.text = "loading" 107 | } 108 | 109 | override fun onLoadingSuccess(key: Long, file: ExtFile) { 110 | sample_file_container_4_info.text = file.toString() 111 | 112 | Picasso.get() 113 | .load(file.file) 114 | .memoryPolicy(MemoryPolicy.NO_CACHE) 115 | .into(sample_file_container_4_iv) 116 | } 117 | 118 | override fun onLoadingFailure(key: Long, throwable: Throwable) { 119 | sample_file_container_4_info.text = throwable.message 120 | } 121 | 122 | }) 123 | pickerFragment.show() 124 | } 125 | 126 | sample_miltiple_select.setOnClickListener { 127 | multipleSelect = !multipleSelect 128 | sample_miltiple_select.isChecked = !sample_miltiple_select.isChecked 129 | } 130 | 131 | sample_disable_camera.setOnClickListener { 132 | cameraDisabled = !cameraDisabled 133 | sample_disable_camera.isChecked = !sample_disable_camera.isChecked 134 | } 135 | 136 | sample_use_custom_layout.setOnClickListener { 137 | useCustomLayout = !useCustomLayout 138 | sample_use_custom_layout.isChecked = !sample_use_custom_layout.isChecked 139 | } 140 | 141 | sample_disable_gallery.setOnClickListener { 142 | galleryDisabled = !galleryDisabled 143 | sample_disable_gallery.isChecked = !sample_disable_gallery.isChecked 144 | } 145 | 146 | sample_disable_files.setOnClickListener { 147 | filesDisabled = !filesDisabled 148 | sample_disable_files.isChecked = !sample_disable_files.isChecked 149 | } 150 | 151 | sample_disable_custom.setOnClickListener { 152 | customActionDisabled = !customActionDisabled 153 | sample_disable_custom.isChecked = !sample_disable_custom.isChecked 154 | } 155 | } 156 | 157 | private fun initFilePickerDialog() = 158 | if (useCustomLayout) { // to user Custom Picker 159 | CustomPicker() 160 | } else { 161 | FilePickerDialog.newInstance() 162 | }.apply { 163 | multipleSelect = this@SampleActivity.multipleSelect //multipe files\photo select 164 | showCamera = !cameraDisabled // to show camera picker row 165 | showGallery = !galleryDisabled // to show gallery picker row 166 | showFileSystem = !filesDisabled // to show file system picker row 167 | 168 | if (!customActionDisabled) { // to use custom action 169 | addCustomAction(CustomActionItem(R.drawable.file_picker_ic_folder, 170 | R.string.fpd_load_from_medical_note_documents, 171 | View.OnClickListener { 172 | Toast.makeText(context, "1 $context", Toast.LENGTH_SHORT).show() 173 | }) 174 | ) 175 | } 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 11 | 16 | 21 | 26 | 31 | 36 | 41 | 46 | 51 | 56 | 61 | 66 | 71 | 76 | 81 | 86 | 91 | 96 | 101 | 106 | 111 | 116 | 121 | 126 | 131 | 136 | 141 | 146 | 151 | 156 | 161 | 166 | 171 | 172 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 16 | 17 | 24 | 25 | 31 | 32 | 39 | 40 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_sample.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 14 | 22 | 23 | 28 | 29 | 35 | 36 | 37 | 38 | 46 | 47 | 52 | 53 | 59 | 60 | 61 | 62 | 70 | 71 | 76 | 77 | 83 | 84 | 85 | 86 | 94 | 95 | 100 | 101 | 107 | 108 | 109 | 110 | 121 | 122 | 123 | 134 | 135 | 136 | 147 | 148 | 149 | 160 | 161 | 162 | 173 | 174 | 175 | 186 | 187 | 188 | 199 | 200 | 201 | -------------------------------------------------------------------------------- /app/src/main/res/layout/file_picker_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | 21 | 22 | 28 | 29 | 35 | 36 | 37 | 45 | 46 | 52 | 53 | 59 | 60 | 61 | 62 | 70 | 71 | 78 | 79 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /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/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16dp 5 | 16sp 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | FilePicker 3 | 4 | Take photo 5 | Choose from gallery 6 | Attach file 7 | Medical Note documents 8 | 9 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/main/res/xml/provider_paths.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | ext.kotlin_version = '1.2.41' 5 | 6 | repositories { 7 | google() 8 | jcenter() 9 | } 10 | dependencies { 11 | classpath 'com.android.tools.build:gradle:3.1.2' 12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 13 | 14 | // NOTE: Do not place your application dependencies here; they belong 15 | // in the individual module build.gradle files 16 | } 17 | } 18 | 19 | allprojects { 20 | repositories { 21 | google() 22 | jcenter() 23 | } 24 | } 25 | 26 | task clean(type: Delete) { 27 | delete rootProject.buildDir 28 | } 29 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx1536m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Mar 27 11:15:35 MSK 2018 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-4.4-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /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 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 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 Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /library/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | apply plugin: 'kotlin-android-extensions' 4 | 5 | ext { 6 | PUBLISH_GROUP_ID = 'org.shagi' 7 | PUBLISH_ARTIFACT_ID = 'filepicker' 8 | PUBLISH_VERSION = '0.4' 9 | } 10 | 11 | android { 12 | compileSdkVersion 27 13 | 14 | defaultConfig { 15 | minSdkVersion 14 16 | targetSdkVersion 27 17 | versionCode 4 18 | versionName "0.4" 19 | 20 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 21 | vectorDrawables.useSupportLibrary = true 22 | } 23 | 24 | buildTypes { 25 | release { 26 | minifyEnabled false 27 | } 28 | } 29 | 30 | lintOptions { 31 | abortOnError false 32 | } 33 | } 34 | 35 | dependencies { 36 | implementation fileTree(dir: 'libs', include: ['*.jar']) 37 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 38 | 39 | implementation 'com.android.support:appcompat-v7:27.1.1' 40 | 41 | implementation "com.android.support:exifinterface:27.1.1" 42 | implementation "com.android.support:design:27.1.1" 43 | implementation "com.android.support:support-v4:27.1.1" 44 | } 45 | 46 | apply from: 'https://raw.githubusercontent.com/blundell/release-android-library/master/android-release-aar.gradle' -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/CacheController.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.content.Context 4 | import android.graphics.Bitmap 5 | import android.net.Uri 6 | import android.provider.OpenableColumns 7 | import java.io.ByteArrayOutputStream 8 | import java.io.File 9 | import java.io.FileOutputStream 10 | 11 | private const val MAX_CACHE_SIZE = 52_428_800L //50 MB 12 | private const val MAX_FILE_SIZE = 10_485_760L //10MB 13 | 14 | class CacheController constructor(val context: Context) { 15 | 16 | var maxCacheSize = MAX_CACHE_SIZE 17 | var maxFileSize = MAX_FILE_SIZE 18 | 19 | private val cacheDir = File(context.cacheDir, "files_cache") 20 | 21 | init { 22 | if (!cacheDir.exists()) { 23 | cacheDir.mkdirs() 24 | } 25 | } 26 | 27 | fun setup(maxCacheSize: Long, maxFileSize: Long) { 28 | if (maxFileSize > maxCacheSize) { 29 | throw IllegalStateException("max file size couldn't be greater then max cache size") 30 | } 31 | 32 | this.maxCacheSize = maxCacheSize 33 | this.maxFileSize = maxFileSize 34 | } 35 | 36 | @Throws(MaxCacheFileSizeException::class) 37 | fun saveBitmap(bitmap: Bitmap): ExtFile { 38 | 39 | val currentSize = getDirSize(cacheDir) 40 | val imageFile = File(cacheDir, "image_" + System.currentTimeMillis() + ".jpg") 41 | 42 | ByteArrayOutputStream().use { 43 | val byteOutput = it; 44 | bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteOutput) 45 | it.flush() 46 | 47 | val size = it.size() 48 | 49 | if (size > maxFileSize) { 50 | throw MaxCacheFileSizeException() 51 | } 52 | 53 | if (currentSize + size > maxCacheSize) { 54 | cleanSpace(cacheDir, (currentSize + size) - maxCacheSize) 55 | } 56 | 57 | FileOutputStream(imageFile).use { 58 | byteOutput.writeTo(it) 59 | } 60 | } 61 | 62 | return ExtFile(imageFile, null, imageFile.name, imageFile.extension, getMimeType(imageFile)) 63 | } 64 | 65 | @Throws(MaxCacheFileSizeException::class) 66 | fun saveFile(uri: Uri): ExtFile { 67 | 68 | val cursor = context.contentResolver.query(uri, null, null, null, null) 69 | cursor?.moveToFirst() 70 | 71 | val name = cursor?.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) 72 | ?: uri.lastPathSegment 73 | 74 | val size = cursor?.getLong(cursor.getColumnIndex(OpenableColumns.SIZE)) 75 | 76 | if (size != null && size > maxFileSize) { 77 | throw MaxCacheFileSizeException() 78 | } 79 | 80 | val inputStream = context.contentResolver.openInputStream(uri) 81 | 82 | if (size == null && inputStream.available() > maxFileSize) { 83 | throw MaxCacheFileSizeException() 84 | } 85 | 86 | val currentSize = getDirSize(cacheDir) 87 | val newSize = currentSize + inputStream.available() 88 | 89 | if (newSize > maxCacheSize) { 90 | cleanSpace(cacheDir, newSize - maxCacheSize) 91 | } 92 | 93 | val file = File(cacheDir, name) 94 | 95 | val outputStream = FileOutputStream(file) 96 | 97 | val buffer = ByteArray(inputStream.available()) 98 | inputStream.read(buffer) 99 | outputStream.write(buffer) 100 | 101 | outputStream.flush() 102 | cursor?.close() 103 | 104 | val ext = file.extension 105 | 106 | return ExtFile(file, uri, name, ext, getMimeType(ext)) 107 | } 108 | 109 | private fun cleanSpace(dir: File, bytes: Long) { 110 | var bytesDeleted = 0L 111 | dir.listFiles() 112 | .filter { it.isFile } 113 | .sortedBy { it.lastModified() } 114 | .forEach { 115 | bytesDeleted += it.length() 116 | it.delete() 117 | if (bytesDeleted > bytes) { 118 | return 119 | } 120 | } 121 | } 122 | 123 | private fun getDirSize(dir: File): Long { 124 | var size = 0L 125 | dir.listFiles().forEach { size += it.length() } 126 | return size 127 | } 128 | 129 | class MaxCacheFileSizeException : IllegalArgumentException("File size limit exceeded") 130 | } -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/CustomActionItem.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.content.Context 4 | import android.support.annotation.DrawableRes 5 | import android.support.annotation.StringRes 6 | import android.view.LayoutInflater 7 | import android.view.View 8 | import android.view.ViewGroup 9 | import kotlinx.android.synthetic.main.file_picker_action_layout.view.* 10 | 11 | class CustomActionItem(@DrawableRes private val icon: Int, 12 | @StringRes private val title: Int, 13 | private val listener: View.OnClickListener) { 14 | 15 | fun generateView(ctx: Context, parent: ViewGroup): View { 16 | val view = LayoutInflater.from(ctx).inflate(R.layout.file_picker_action_layout, parent, false) 17 | view.setOnClickListener(listener) 18 | view.file_picker_custom_action_icon.setImageResource(icon) 19 | view.file_picker_custom_action_title.setText(title) 20 | return view 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/ExtFile.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.net.Uri 4 | import java.io.File 5 | 6 | data class ExtFile(val file: File, 7 | val baseUri: Uri? = null, 8 | val name: String? = null, 9 | val extension: String? = null, 10 | val mimeType: String? = null) { 11 | 12 | override fun toString(): String { 13 | return """ 14 | File: $file 15 | Uri: $baseUri 16 | Name: $name 17 | Extension: $extension 18 | MimeType: $mimeType 19 | """.trimIndent() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FilePicker.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.content.Context 4 | import android.net.Uri 5 | import android.os.AsyncTask 6 | import android.support.v4.app.FragmentManager 7 | 8 | class FilePicker(var context: Context?, private val useCache: Boolean = false) : FilePickerDialog.OnFilePickedListener { 9 | 10 | private lateinit var mDialog: FilePickerDialog 11 | 12 | private var mCacheController: CacheController? = null 13 | private var loadingListener: OnLoadingListener? = null 14 | 15 | private var width = 1024 16 | private var height = 1024 17 | 18 | private var tasks = ArrayList() 19 | 20 | init { 21 | context?.let { 22 | if (useCache) { 23 | mCacheController = CacheController(it) 24 | } 25 | } 26 | } 27 | 28 | fun setup(settings: FilePickerSettings) { 29 | width = settings.maxWidth 30 | height = settings.maxHeight 31 | mCacheController?.setup(settings.maxCacheSize, settings.maxFileSize) 32 | } 33 | 34 | fun with(filePickerDialog: FilePickerDialog) { 35 | mDialog = filePickerDialog 36 | } 37 | 38 | fun subscribe(supportFragmentManager: FragmentManager) { 39 | mDialog.filePickedListener = this 40 | mDialog.show(supportFragmentManager, FilePickerDialog.TAG) 41 | } 42 | 43 | fun detach() { 44 | loadingListener = null 45 | tasks.forEach { it.setLoadingListener(null) } 46 | } 47 | 48 | fun setLoadingListener(_loadingListener: OnLoadingListener) { 49 | loadingListener = _loadingListener 50 | tasks.forEach { it.setLoadingListener(_loadingListener) } 51 | } 52 | 53 | fun dispose() { 54 | detach() 55 | tasks.clear() 56 | context = null 57 | } 58 | 59 | override fun onFilePicked(uri: Uri, fileType: FileType, fromCamera: Boolean) { 60 | context?.let { 61 | tasks.add(SaveFileAsyncTask(it, mCacheController, fileType, fromCamera).apply { 62 | loadingListener?.let { 63 | setLoadingListener(it) 64 | executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, uri) 65 | } 66 | }) 67 | } 68 | } 69 | 70 | override fun onFilePickFailed() { 71 | loadingListener?.onLoadingFailure(FILE_NOT_UPLOADED, IllegalStateException("File not uploaded")) 72 | } 73 | 74 | interface OnLoadingListener { 75 | /** 76 | * Invokes when file start loading. When you are trying to get photos/files 77 | * from remote source (Google drive, Dropbox etc.) it can take long time so you may want to show progress. 78 | * @param key - key for current loading file. 79 | */ 80 | fun onLoadingStart(key: Long) 81 | fun onLoadingSuccess(key: Long, file: ExtFile) 82 | fun onLoadingFailure(key: Long, throwable: Throwable) 83 | } 84 | 85 | companion object { 86 | const val FILE_NOT_UPLOADED = -1L 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FilePickerDialog.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.Activity 5 | import android.content.ClipData 6 | import android.content.Intent 7 | import android.content.pm.PackageManager 8 | import android.net.Uri 9 | import android.os.Build 10 | import android.os.Bundle 11 | import android.support.design.widget.BottomSheetDialogFragment 12 | import android.view.LayoutInflater 13 | import android.view.View 14 | import android.view.ViewGroup 15 | import android.widget.LinearLayout 16 | import kotlinx.android.synthetic.main.file_picker_dialog_layout.* 17 | 18 | open class FilePickerDialog : BottomSheetDialogFragment() { 19 | 20 | private lateinit var resolver: IntentResolver 21 | 22 | var filePickedListener: OnFilePickedListener? = null 23 | private var isCameraStarting = false 24 | private val customActions = ArrayList() 25 | 26 | var showCamera = true 27 | var showGallery = true 28 | var showFileSystem = true 29 | var multipleSelect = false 30 | 31 | override fun onCreate(savedInstanceState: Bundle?) { 32 | super.onCreate(savedInstanceState) 33 | retainInstance = true 34 | resolver = IntentResolver(requireActivity()) 35 | } 36 | 37 | override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = 38 | inflater.inflate(R.layout.file_picker_dialog_layout, container, false) 39 | 40 | final override fun onViewCreated(view: View, savedInstanceState: Bundle?) { 41 | 42 | if (!showCamera && !showGallery && !showFileSystem && customActions.isEmpty()) { 43 | dismissAllowingStateLoss() 44 | } 45 | 46 | if (showCamera) { 47 | file_picker_camera.setOnClickListener { 48 | isCameraStarting = true 49 | resolver.launchCamera(this) 50 | } 51 | } else { 52 | file_picker_camera.visibility = View.GONE 53 | } 54 | 55 | if (showGallery) { 56 | file_picker_gallery.setOnClickListener { 57 | isCameraStarting = false 58 | resolver.launchGallery(this, multipleSelect) 59 | } 60 | } else { 61 | file_picker_gallery.visibility = View.GONE 62 | } 63 | 64 | if (showFileSystem) { 65 | file_picker_files.setOnClickListener { onFilesOpenClick() } 66 | } else { 67 | file_picker_files.visibility = View.GONE 68 | } 69 | 70 | initCustomActions(view) 71 | } 72 | 73 | open fun initCustomActions(view: View) { 74 | customActions.forEach { 75 | (view as ViewGroup).addView(it.generateView(requireContext(), view)) 76 | } 77 | } 78 | 79 | private fun onFilesOpenClick() { 80 | val intent = Intent(Intent.ACTION_GET_CONTENT) 81 | intent.addCategory(Intent.CATEGORY_OPENABLE) 82 | 83 | if (multipleSelect && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 84 | intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) 85 | } 86 | 87 | intent.type = "*/*" 88 | startActivityForResult(intent, IntentResolver.REQUESTER) 89 | } 90 | 91 | fun addCustomAction(customActionItem: CustomActionItem) { 92 | customActions.add(customActionItem) 93 | } 94 | 95 | override fun onDestroyView() { 96 | if (dialog != null && retainInstance) { 97 | dialog.setDismissMessage(null) 98 | } 99 | super.onDestroyView() 100 | } 101 | 102 | @SuppressLint("NewApi") 103 | final override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { 104 | super.onActivityResult(requestCode, resultCode, data) 105 | if (requestCode == IntentResolver.REQUESTER && resultCode == Activity.RESULT_OK) { 106 | val isFromCamera = resolver.fromCamera(data) 107 | if (data?.data != null || isFromCamera) { 108 | val fileType = getFileType(data) 109 | val uri = getUri(data) 110 | 111 | uri?.let { 112 | filePickedListener?.onFilePicked(uri, fileType, isFromCamera) 113 | } 114 | } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && data?.clipData != null) { 115 | val clipData = data.clipData 116 | (0 until clipData.itemCount) 117 | .map(clipData::getItemAt) 118 | .map(ClipData.Item::getUri) 119 | .filterNotNull() 120 | .forEach { filePickedListener?.onFilePicked(it, getFileType(it), false) } 121 | } 122 | } 123 | 124 | dismissAllowingStateLoss() 125 | } 126 | 127 | final override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { 128 | super.onRequestPermissionsResult(requestCode, permissions, grantResults) 129 | if (requestCode == IntentResolver.REQUESTER) { 130 | var granted = true 131 | 132 | for (i in grantResults) { 133 | granted = granted && i == PackageManager.PERMISSION_GRANTED 134 | } 135 | 136 | if (granted) { 137 | if (isCameraStarting) { 138 | resolver.launchCamera(this) 139 | } else { 140 | resolver.launchGallery(this, multipleSelect) 141 | } 142 | } else { 143 | dismissAllowingStateLoss() 144 | } 145 | } 146 | } 147 | 148 | //----------------------------------------------------------------------------------------------- 149 | 150 | private fun getFileType(data: Intent?): FileType { 151 | if (resolver.fromCamera(data)) return FileType.IMAGE 152 | 153 | val uri = data?.data 154 | return getFileType(uri) 155 | } 156 | 157 | private fun getFileType(uri: Uri?): FileType { 158 | val isImage = uri?.let { 159 | requireContext().contentResolver.getType(it) 160 | }?.contains("image/") == true 161 | 162 | if (isImage) return FileType.IMAGE 163 | 164 | return FileType.FILE 165 | } 166 | 167 | private fun getUri(data: Intent?) = if (resolver.fromCamera(data)) { 168 | resolver.cameraUri() 169 | } else { 170 | data?.data 171 | } 172 | 173 | //----------------------------------------------------------------------------------------------- 174 | 175 | interface OnFilePickedListener { 176 | fun onFilePicked(uri: Uri, fileType: FileType, fromCamera: Boolean) 177 | fun onFilePickFailed() 178 | } 179 | 180 | companion object { 181 | const val TAG = "FilePickerDialog" 182 | 183 | @JvmStatic 184 | fun newInstance(): FilePickerDialog { 185 | val fragment = FilePickerDialog() 186 | 187 | return fragment 188 | } 189 | } 190 | } -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FilePickerFragment.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.os.Bundle 4 | import android.support.v4.app.Fragment 5 | import android.support.v4.app.FragmentManager 6 | 7 | class FilePickerFragment : Fragment() { 8 | 9 | private var filePickerDialog: FilePickerDialog? = null 10 | private lateinit var picker: FilePicker 11 | private var filePickerSettings: FilePickerSettings? = null 12 | 13 | override fun onCreate(savedInstanceState: Bundle?) { 14 | super.onCreate(savedInstanceState) 15 | retainInstance = true 16 | 17 | val useCache = arguments?.getBoolean(ARG_USE_CACHE) == true 18 | picker = FilePicker(requireContext().applicationContext, useCache) 19 | } 20 | 21 | override fun onDetach() { 22 | if (requireActivity().isFinishing) { 23 | picker.dispose() 24 | } else { 25 | picker.detach() 26 | } 27 | super.onDetach() 28 | } 29 | 30 | fun setOnLoadingListener(_loadingListener: FilePicker.OnLoadingListener) { 31 | picker.setLoadingListener(_loadingListener) 32 | } 33 | 34 | fun use(filePickerDialog: FilePickerDialog) { 35 | this.filePickerDialog = filePickerDialog 36 | } 37 | 38 | fun setup(settings: FilePickerSettings) { 39 | filePickerSettings = settings 40 | } 41 | 42 | fun show() { 43 | filePickerSettings?.let { 44 | picker.setup(it) 45 | } 46 | picker.with(filePickerDialog ?: FilePickerDialog.newInstance()) 47 | picker.subscribe(requireFragmentManager()) 48 | } 49 | 50 | companion object { 51 | private const val FRAGMENT_TAG = "FilePickerFragment" 52 | private const val ARG_USE_CACHE = "use_cache" 53 | 54 | fun getFragment(fragmentManager: FragmentManager, useCache: Boolean = false): FilePickerFragment { 55 | var fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG) as? FilePickerFragment 56 | 57 | if (fragment == null) { 58 | fragment = FilePickerFragment().apply { 59 | val bundle = Bundle() 60 | bundle.putBoolean(ARG_USE_CACHE, useCache) 61 | arguments = bundle 62 | } 63 | 64 | fragmentManager.beginTransaction().add(fragment, FRAGMENT_TAG).commitNowAllowingStateLoss() 65 | } 66 | 67 | return fragment 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FilePickerSettings.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | class FilePickerSettings { 4 | var maxWidth: Int = 1024 5 | var maxHeight: Int = 1024 6 | var maxCacheSize: Long = 52_428_800L 7 | var maxFileSize: Long = 10_485_760L 8 | } 9 | -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FilePickerUtils.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.content.Context 4 | import android.database.Cursor 5 | import android.graphics.Bitmap 6 | import android.net.Uri 7 | import android.provider.OpenableColumns 8 | import android.util.Log 9 | import android.webkit.MimeTypeMap 10 | import java.io.ByteArrayOutputStream 11 | import java.io.File 12 | import java.io.FileOutputStream 13 | 14 | const val TEMP_FILE = "temp_file" 15 | 16 | fun getPath(context: Context, uri: Uri): String? { 17 | if ("content".equals(uri.scheme, ignoreCase = true)) { 18 | return getDataColumn(context, uri) 19 | } else if ("file".equals(uri.scheme, ignoreCase = true)) { 20 | return uri.path 21 | } 22 | 23 | return null 24 | } 25 | 26 | fun getExtension(file: File): String { 27 | return file.extension 28 | } 29 | 30 | fun getMimeType(file: File): String? { 31 | var mimeType: String? = null 32 | 33 | val extension = MimeTypeMap.getFileExtensionFromUrl(file.path) 34 | 35 | if (MimeTypeMap.getSingleton().hasExtension(extension)) { 36 | mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) 37 | } 38 | return mimeType 39 | } 40 | 41 | fun getMimeType(extension: String): String? = 42 | if (MimeTypeMap.getSingleton().hasExtension(extension)) { 43 | MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) 44 | } else null 45 | 46 | fun getDataColumn(context: Context, uri: Uri): String? { 47 | 48 | var cursor: Cursor? = null 49 | val column = "_data" 50 | val projection = arrayOf(column) 51 | 52 | try { 53 | cursor = context.contentResolver.query(uri, projection, null, null, null) 54 | if (cursor != null && cursor.moveToFirst()) { 55 | val columnIndex = cursor.getColumnIndexOrThrow(column) 56 | return cursor.getString(columnIndex) 57 | } 58 | } finally { 59 | if (cursor != null) 60 | cursor.close() 61 | } 62 | return null 63 | } 64 | 65 | fun saveTempFileUri(context: Context, uri: Uri): ExtFile { 66 | val cursor = context.contentResolver.query(uri, null, null, null, null) 67 | cursor?.moveToFirst() 68 | 69 | 70 | val name = cursor?.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)) 71 | ?: uri.lastPathSegment 72 | 73 | val ext = name.split(".").last() 74 | 75 | val mimeType = getMimeType(ext) 76 | 77 | Log.d("QWERTY", "$name, $ext, $mimeType") 78 | 79 | val inputStream = context.contentResolver.openInputStream(uri) 80 | val file = File(context.filesDir, TEMP_FILE) 81 | val outputStream = FileOutputStream(file) 82 | 83 | val buffer = ByteArray(inputStream.available()) 84 | inputStream.read(buffer) 85 | outputStream.write(buffer) 86 | 87 | outputStream.flush() 88 | 89 | cursor.close() 90 | 91 | return ExtFile(file, uri, name, ext, mimeType) 92 | } 93 | 94 | fun saveTempBitmap(context: Context, bitmap: Bitmap): ExtFile { 95 | 96 | val imageFile = File(context.filesDir, TEMP_FILE) 97 | 98 | ByteArrayOutputStream().use { 99 | val byteOutput = it; 100 | bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteOutput) 101 | it.flush() 102 | 103 | FileOutputStream(imageFile).use { 104 | byteOutput.writeTo(it) 105 | } 106 | } 107 | 108 | val ext = "jpg" 109 | 110 | return ExtFile(imageFile, null, imageFile.name, ext, getMimeType(ext)) 111 | } -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/FileType.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | enum class FileType() { 4 | FILE, 5 | IMAGE; 6 | } -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/IntentResolver.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.Manifest 4 | import android.app.Activity 5 | import android.content.Intent 6 | import android.content.pm.PackageManager 7 | import android.net.Uri 8 | import android.os.Build 9 | import android.provider.MediaStore 10 | import android.support.v4.app.Fragment 11 | import android.support.v4.content.ContextCompat 12 | import android.support.v4.content.FileProvider 13 | import java.io.File 14 | import java.util.* 15 | 16 | class IntentResolver(private val activity: Activity) { 17 | 18 | private var galleryIntent: Intent? = null 19 | private var cameraIntent: Intent? = null 20 | private var saveFile: File? = null 21 | 22 | private fun loadSystemPackages(intent: Intent): Intent { 23 | val resInfo = activity.packageManager.queryIntentActivities(intent, PackageManager.MATCH_SYSTEM_ONLY) 24 | 25 | if (!resInfo.isEmpty()) { 26 | val packageName = resInfo[0].activityInfo.packageName 27 | intent.`package` = packageName 28 | } 29 | 30 | return intent 31 | } 32 | 33 | private fun getCameraIntent(): Intent { 34 | if (cameraIntent == null) { 35 | cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) 36 | cameraIntent?.putExtra(MediaStore.EXTRA_OUTPUT, cameraUriForProvider()) 37 | 38 | applyProviderPermission() 39 | } 40 | 41 | return cameraIntent ?: throw IllegalStateException() 42 | } 43 | 44 | /** 45 | * Granting permissions to write and read for available cameras to file provider. 46 | */ 47 | private fun applyProviderPermission() { 48 | val resInfoList = activity.packageManager.queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY) 49 | for (resolveInfo in resInfoList) { 50 | val packageName = resolveInfo.activityInfo.packageName 51 | activity.grantUriPermission(packageName, cameraUriForProvider(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) 52 | } 53 | } 54 | 55 | private fun cameraFile(): File { 56 | if (saveFile == null) { 57 | val directory = File(activity.filesDir, "picked") 58 | directory.mkdirs() 59 | saveFile = File(directory, "current") 60 | } 61 | 62 | return saveFile ?: throw IllegalStateException("file have to be created") 63 | } 64 | 65 | fun cameraUri(): Uri { 66 | return Uri.fromFile(cameraFile()) 67 | } 68 | 69 | private fun getAuthority(): String { 70 | return activity.application.packageName + ".provider" 71 | } 72 | 73 | private fun cameraUriForProvider(): Uri { 74 | try { 75 | return FileProvider.getUriForFile(activity, getAuthority(), cameraFile()) 76 | } catch (e: Exception) { 77 | if (e.message?.contains("ProviderInfo.loadXmlMetaData") == true) { 78 | throw Error("wrong_authority") 79 | } else { 80 | throw e 81 | } 82 | } 83 | } 84 | 85 | private fun getGalleryIntent(multipleSelect: Boolean): Intent { 86 | if (galleryIntent == null) { 87 | galleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) 88 | galleryIntent?.type = "image/*" 89 | 90 | if (multipleSelect && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 91 | galleryIntent?.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true) 92 | } 93 | } 94 | 95 | return galleryIntent ?: throw IllegalStateException("intent must be created") 96 | } 97 | 98 | fun launchCamera(listener: Fragment) { 99 | if (requestPermissions(listener, getCameraPermissions()) && getCameraIntent().resolveActivity(activity.packageManager) != null) { 100 | listener.startActivityForResult(loadSystemPackages(getCameraIntent()), REQUESTER) 101 | } 102 | } 103 | 104 | fun launchGallery(listener: Fragment, multipleSelect: Boolean) { 105 | if (requestPermissions(listener, getGalleryPermissions())) { 106 | listener.startActivityForResult(loadSystemPackages(getGalleryIntent(multipleSelect)), REQUESTER) 107 | } 108 | } 109 | 110 | private fun getCameraPermissions(): Array { 111 | return arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE) 112 | } 113 | 114 | private fun getGalleryPermissions(): Array { 115 | return arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE) 116 | } 117 | 118 | private fun requestPermissions(listener: Fragment, permissions: Array): Boolean { 119 | val list = ArrayList() 120 | 121 | for (permission in permissions) 122 | if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_DENIED) 123 | list.add(permission) 124 | 125 | if (list.isEmpty()) 126 | return true 127 | 128 | listener.requestPermissions(list.toTypedArray(), REQUESTER) 129 | return false 130 | } 131 | 132 | fun fromCamera(data: Intent?): Boolean { 133 | return data == null || data.data == null || data.data.toString().contains(cameraFile().toString()) 134 | } 135 | 136 | fun getActivity(): Activity { 137 | return activity 138 | } 139 | 140 | companion object { 141 | const val REQUESTER = 99 142 | } 143 | } -------------------------------------------------------------------------------- /library/src/main/java/org/shagi/filepicker/SaveFileAsyncTask.kt: -------------------------------------------------------------------------------- 1 | package org.shagi.filepicker 2 | 3 | import android.content.Context 4 | import android.graphics.Bitmap 5 | import android.graphics.BitmapFactory 6 | import android.graphics.Matrix 7 | import android.net.Uri 8 | import android.os.AsyncTask 9 | import android.support.media.ExifInterface 10 | import java.io.FileNotFoundException 11 | import java.lang.ref.WeakReference 12 | 13 | class SaveFileAsyncTask internal constructor(context: Context, 14 | cacheController: CacheController?, 15 | private val fileType: FileType, 16 | private val isFromCamera: Boolean) : AsyncTask() { 17 | 18 | private var key: Long = 0 19 | private var throwable: Throwable? = null 20 | 21 | private val weakContext = WeakReference(context) 22 | private var weakListener: WeakReference? = null 23 | private var weakCacheController: WeakReference? = null 24 | 25 | private var width = 1024 26 | private var height = 1024 27 | 28 | init { 29 | cacheController?.let { weakCacheController = WeakReference(cacheController) } 30 | } 31 | 32 | internal fun setLoadingListener(loadingListener: FilePicker.OnLoadingListener?) { 33 | weakListener = WeakReference(loadingListener) 34 | } 35 | 36 | override fun onPreExecute() { 37 | key = System.currentTimeMillis() 38 | val loadingListener = weakListener?.get() 39 | loadingListener?.onLoadingStart(key) ?: cancel(false) 40 | } 41 | 42 | override fun doInBackground(vararg uris: Uri): ExtFile? { 43 | if (isCancelled) return null 44 | 45 | weakContext.get()?.let { 46 | return saveToFile(it, uris[0], fileType, isFromCamera) 47 | } 48 | 49 | return null 50 | } 51 | 52 | override fun onPostExecute(file: ExtFile?) { 53 | val loadingListener = weakListener?.get() 54 | 55 | loadingListener?.let { 56 | throwable?.let { 57 | loadingListener.onLoadingFailure(key, it) 58 | return 59 | } 60 | if (file != null) { 61 | loadingListener.onLoadingSuccess(key, file) 62 | } 63 | } 64 | } 65 | 66 | //--------------------------------------------------------------------------------------------- 67 | 68 | private fun saveToFile(context: Context, uri: Uri, fileType: FileType, isFromCamera: Boolean): ExtFile { 69 | return if (fileType == FileType.FILE) { 70 | saveFile(context, uri) 71 | } else { 72 | savePhoto(context, uri, isFromCamera) 73 | } 74 | } 75 | 76 | private fun saveFile(context: Context, uri: Uri): ExtFile { 77 | weakCacheController?.get()?.let { 78 | return it.saveFile(uri) 79 | } 80 | 81 | return saveTempFileUri(context, uri) 82 | } 83 | 84 | private fun savePhoto(context: Context, uri: Uri, isFromCamera: Boolean): ExtFile { 85 | val bitmap = if (width - height == 0) { 86 | scaleDown(context, uri) 87 | } else { 88 | resize(context, uri) 89 | } 90 | 91 | weakCacheController?.get()?.let { 92 | return it.saveBitmap(rotateIfNeeded(context, bitmap, uri, isFromCamera)) 93 | } 94 | 95 | return saveTempBitmap(context, rotateIfNeeded(context, bitmap, uri, isFromCamera)) 96 | } 97 | 98 | 99 | private fun rotateIfNeeded(context: Context, bitmap: Bitmap, uri: Uri, isFromCamera: Boolean): Bitmap { 100 | 101 | val path = if (isFromCamera) { 102 | uri.path 103 | } else { 104 | getPath(context, uri) 105 | } 106 | 107 | val exif = if (path != null) { 108 | ExifInterface(path) 109 | } else { 110 | ExifInterface(context.contentResolver.openInputStream(uri)) 111 | } 112 | 113 | val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL) 114 | 115 | val rotate = when (orientation) { 116 | ExifInterface.ORIENTATION_ROTATE_270 -> 270 117 | ExifInterface.ORIENTATION_ROTATE_180 -> 180 118 | ExifInterface.ORIENTATION_ROTATE_90 -> 90 119 | else -> 0 120 | } 121 | 122 | return rotate(bitmap, rotate) 123 | } 124 | 125 | private fun rotate(bitmap: Bitmap, degrees: Int): Bitmap { 126 | if (degrees != 0) { 127 | val matrix = Matrix() 128 | matrix.postRotate(degrees.toFloat()) 129 | return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) 130 | } 131 | 132 | return bitmap 133 | } 134 | 135 | @Throws(FileNotFoundException::class) 136 | private fun getOptions(context: Context, uri: Uri): BitmapFactory.Options { 137 | var options = BitmapFactory.Options() 138 | options.inJustDecodeBounds = true 139 | BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri), null, options) 140 | 141 | var w = options.outWidth 142 | var h = options.outHeight 143 | var scale = 1 144 | while (true) { 145 | if (w / 2 < width || h / 2 < height) 146 | break 147 | 148 | w /= 2 149 | h /= 2 150 | scale *= 2 151 | } 152 | 153 | options = BitmapFactory.Options() 154 | options.inSampleSize = scale 155 | return options 156 | } 157 | 158 | 159 | @Throws(FileNotFoundException::class) 160 | private fun scaleDown(context: Context, uri: Uri): Bitmap { 161 | return BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri), null, getOptions(context, uri)) 162 | } 163 | 164 | @Throws(FileNotFoundException::class) 165 | private fun resize(context: Context, uri: Uri): Bitmap { 166 | return Bitmap.createScaledBitmap(scaleDown(context, uri), width, height, false) 167 | } 168 | 169 | //---------------------------------------------------------------------------------------------- 170 | 171 | } 172 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/file_picker_ic_camera.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/file_picker_ic_file_upload.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/file_picker_ic_folder.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /library/src/main/res/drawable/file_picker_ic_image.xml: -------------------------------------------------------------------------------- 1 | 6 | 9 | 10 | -------------------------------------------------------------------------------- /library/src/main/res/layout/file_picker_action_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 13 | 14 | 22 | 23 | 31 | -------------------------------------------------------------------------------- /library/src/main/res/layout/file_picker_dialog_layout.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 16 | 17 | 24 | 25 | 33 | 34 | 35 | 43 | 44 | 51 | 52 | 60 | 61 | 62 | 70 | 71 | 78 | 79 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /library/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16sp 5 | -------------------------------------------------------------------------------- /library/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Take photo 3 | Choose from gallery 4 | Attach file 5 | 6 | -------------------------------------------------------------------------------- /screenshot_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/screenshot_1.jpg -------------------------------------------------------------------------------- /screenshot_2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/screenshot_2.jpg -------------------------------------------------------------------------------- /screenshot_3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shagiz/AsyncFilePicker/2818b0485508b206e7b9aa903b2aaa0c045c7c9b/screenshot_3.jpg -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':library' 2 | --------------------------------------------------------------------------------