├── .gitignore ├── LICENSE ├── README.md ├── async ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── mcxiaoke │ └── koi │ └── async │ ├── Async.kt │ ├── Context.kt │ ├── Executor.kt │ └── Thread.kt ├── base.gradle ├── build.gradle ├── core ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── mcxiaoke │ └── koi │ ├── Constants.kt │ ├── Core.kt │ ├── Crypto.kt │ ├── adapter │ ├── ArrayAdapterEx.kt │ ├── QuickAdapter.kt │ └── QuickViewBinder.kt │ ├── assert │ └── Preconditions.kt │ ├── ext │ ├── Activity.kt │ ├── Adapter.kt │ ├── Application.kt │ ├── Bundle.kt │ ├── Collections.kt │ ├── Context.kt │ ├── Cursor.kt │ ├── Database.kt │ ├── Date.kt │ ├── Functions.kt │ ├── Handler.kt │ ├── IO.kt │ ├── Intent.kt │ ├── Math.kt │ ├── Network.kt │ ├── Package.kt │ ├── Parcelable.kt │ ├── Primitives.kt │ ├── String.kt │ ├── SystemService.kt │ ├── Toast.kt │ └── View.kt │ ├── log │ └── Log.kt │ └── utils │ ├── Platform.kt │ └── System.kt ├── deploy-local.sh ├── deploy-remote.sh ├── docs └── kotlin-tutorial-basic01.md ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── network ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ └── kotlin │ └── com │ └── mcxiaoke │ └── koi │ └── network │ └── NetworkConfig.kt ├── samples ├── build.gradle ├── gradle.properties └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── mcxiaoke │ │ └── koi │ │ └── samples │ │ ├── JavaApplication.java │ │ ├── JavaFragment.java │ │ ├── JavaFragmentV4.java │ │ ├── JavaLayout.java │ │ ├── JavaService.java │ │ ├── JavaSimpleClass.java │ │ └── JavaView.java │ ├── kotlin │ └── com │ │ └── mcxiaoke │ │ └── koi │ │ └── samples │ │ ├── AdapterSample.kt │ │ ├── AsyncSample.kt │ │ ├── BundleSample.kt │ │ ├── CollectionSample.kt │ │ ├── ContextSample.kt │ │ ├── CoreSample.kt │ │ ├── CursorSample.kt │ │ ├── DateSample.kt │ │ ├── HandlerSample.kt │ │ ├── IOSample.kt │ │ ├── MiscSample.kt │ │ ├── ViewSample.kt │ │ ├── app │ │ ├── MainActivity.kt │ │ ├── MainApp.kt │ │ ├── MainFragment.kt │ │ └── SplashActivity.kt │ │ ├── json │ │ ├── Gson.kt │ │ └── GsonBuilder.kt │ │ └── tests │ │ └── CoreTests.kt │ └── res │ ├── drawable-xxxhdpi │ └── ic_launcher.png │ ├── layout │ ├── activity_empty.xml │ ├── activity_main.xml │ └── activity_splash.xml │ └── values │ └── strings.xml ├── settings.gradle └── ui ├── build.gradle ├── gradle.properties └── src └── main ├── AndroidManifest.xml └── kotlin └── com └── mcxiaoke └── koi └── ui └── UIConfig.kt /.gitignore: -------------------------------------------------------------------------------- 1 | *.apk 2 | *.dex 3 | bin/ 4 | gen/ 5 | .gradle/ 6 | build/ 7 | local.properties 8 | proguard/ 9 | *.log 10 | .navigation/ 11 | captures/ 12 | *~ 13 | gen 14 | bin 15 | .*.swp 16 | /.classpath 17 | /.project 18 | .idea/ 19 | .settings/ 20 | gen-external-apklibs/ 21 | target/ 22 | classes/ 23 | project.properties 24 | signing.properties 25 | *.iml 26 | .DS_Store 27 | out/ 28 | 29 | -------------------------------------------------------------------------------- /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 | # Koi - A lightweight Kotlin library for Android 2 | 3 | **Koi** include many useful extensions and functions, they can help reducing the boilerplate code in Android applications. Specifically, **Koi** include a powerful extension function named [**asyncSafe**](#async-functions). 4 | 5 | ## Gradle 6 | 7 | Latest Version: [![Maven Central](https://img.shields.io/badge/2017.08.25-com.mcxiaoke.koi:core:0.5.5-brightgreen.svg)](http://search.maven.org/#search%7Cga%7C1%7Cg%3A%22com.mcxiaoke.koi%22) Compiled with Kotlin 1.1.4. 8 | 9 | ```gradle 10 | compile 'com.mcxiaoke.koi:core:0.5.5' // useful extensions (only ~100k) 11 | compile 'com.mcxiaoke.koi:async:0.5.5' // async functions (only ~70k) 12 | ``` 13 | 14 | ## Usage 15 | 16 | 17 | * [Context Extensions](#context-extensions) 18 | * [Activity Functions](#activity-functions) 19 | * [Fragment Functions](#fragment-functions) 20 | * [Easy to use Toast](#easy-to-use-toast) 21 | * [Easy to Inflate Layout](#easy-to-inflate-layout) 22 | * [Useful Functions](#useful-functions) 23 | * [Easy to create Intent](#easy-to-create-intent) 24 | * [Easy to Start Activity](#easy-to-start-activity) 25 | * [Easy to Start Service](#easy-to-start-service) 26 | * [Network State](#network-state) 27 | * [Notification Builder](#notification-builder) 28 | * [Package Functions](#package-functions) 29 | * [System Service](#system-service) 30 | * [Easy to Log](#easy-to-log) 31 | * [View Extensions](#view-extensions) 32 | * [View Listeners 1](#view-listeners-1) 33 | * [View Listeners 2](#view-listeners-2) 34 | * [ListView Listeners](#listview-listeners) 35 | * [View Utils](#view-utils) 36 | * [Adapter Extensions](#adapter-extensions) 37 | * [Easy to Create Adapter](#easy-to-create-adapter) 38 | * [Bundle Extensions](#bundle-extensions) 39 | * [Bundle Builder](#bundle-builder) 40 | * [Parcelable Extensions](#parcelable-extensions) 41 | * [Easy to create Parcelable](#easy-to-create-parcelable) 42 | * [Collection Extensions](#collection-extensions) 43 | * [Collection to String](#collection-to-string) 44 | * [Map to String](#map-to-string) 45 | * [List Append](#list-append) 46 | * [Database Extensions](#database-extensions) 47 | * [Easy to get Cursor Value](#easy-to-get-cursor-value) 48 | * [Easy to convert Cursor to Model](#easy-to-convert-cursor-to-model) 49 | * [Easy to use Transaction](#easy-to-use-transaction) 50 | * [IO Extensions](#io-extensions) 51 | * [Easy to close Stream](#easy-to-close-stream) 52 | * [Stream doSafe Function](#stream-dosafe-function) 53 | * [readString/readList](#readstringreadlist) 54 | * [readString/readList using doSafe](#readstringreadlist-using-dosafe) 55 | * [writeString/writeList using doSafe](#writestringwritelist-using-dosafe) 56 | * [File Read and Write](#file-read-and-write) 57 | * [Handler Extensions](#handler-extensions) 58 | * [Easy to use Handler](#easy-to-use-handler) 59 | * [Other Extensions](#other-extensions) 60 | * [Date Functions](#date-functions) 61 | * [Number Functions](#number-functions) 62 | * [String Functions](#string-functions) 63 | * [Crypto Functions](#crypto-functions) 64 | * [Check API Level](#check-api-level) 65 | * [Device Functions](#device-functions) 66 | * [Preconditions](#preconditions) 67 | * [Thread Functions](#thread-functions) 68 | * [Create Thread Pool](#create-thread-pool) 69 | * [Main Thread Functions](#main-thread-functions) 70 | * [Context Check](#context-check) 71 | * [Safe Functions](#safe-functions) 72 | * [Async Functions](#async-functions) 73 | * [With Context Check 1](#with-context-check-1) 74 | * [With Context Check 2](#with-context-check-2) 75 | * [Without Context Check](#without-context-check) 76 | * [With Delay](#with-delay) 77 | * [Custom Executor](#custom-executor) 78 | 79 | 80 | 81 | 82 | ### Context Extensions 83 | 84 | #### Activity Functions 85 | ```kotlin 86 | // available for Activity 87 | fun activityExtensions() { 88 | val act = getActivity() // Activity 89 | act.restart() // restart Activity 90 | val app = act.getApp() // Application 91 | val app2 = act.application // Application 92 | // Activity.find() 93 | // Fragment.find() 94 | // View.find() 95 | val textView = act.find(android.R.id.text1) 96 | } 97 | ``` 98 | 99 | #### Fragment Functions 100 | ```kotlin 101 | // available for Fragment 102 | fun fragmentExtensions() { 103 | val act = activity // Activity 104 | val app = getApp() // Application 105 | val textView = find(android.R.id.text1) // view.findViewById 106 | val imageView = find(android.R.id.icon1) // view.findViewById 107 | } 108 | ``` 109 | 110 | #### Easy to use Toast 111 | ```kotlin 112 | // available for Context 113 | fun toastExtensions() { 114 | // available in Activity/Fragment/Service/Context 115 | toast(R.string.app_name) 116 | toast("this is a toast") 117 | longToast(R.string.app_name) 118 | longToast("this is a long toast") 119 | } 120 | ``` 121 | 122 | #### Easy to Inflate Layout 123 | ```kotlin 124 | // available for Context 125 | fun inflateLayout() { 126 | val view1 = inflate(R.layout.activity_main) 127 | val viewGroup = view1 as ViewGroup 128 | val view2 = inflate(android.R.layout.activity_list_item, viewGroup, false) 129 | } 130 | ``` 131 | 132 | #### Useful Functions 133 | ```kotlin 134 | // available for Context 135 | fun miscExtensions() { 136 | val hasCamera = hasCamera() 137 | 138 | mediaScan(Uri.parse("file:///sdcard/Pictures/koi/cat.png")) 139 | addToMediaStore(File("/sdcard/Pictures/koi/cat.png")) 140 | 141 | val batteryStatusIntent = getBatteryStatus() 142 | val colorValue = getResourceValue(android.R.color.darker_gray) 143 | } 144 | ``` 145 | 146 | #### Easy to create Intent 147 | ```kotlin 148 | // available for Context 149 | fun intentExtensions() { 150 | val extras = Bundle { putString("key", "value") } 151 | val intent1 = newIntent() 152 | val intent2 = newIntent(Intent.FLAG_ACTIVITY_NEW_TASK, extras) 153 | } 154 | ``` 155 | 156 | #### Easy to Start Activity 157 | ```kotlin 158 | // available for Activity 159 | fun startActivityExtensions() { 160 | startActivity() 161 | // equal to 162 | startActivity(Intent(this, MainActivity::class.java)) 163 | 164 | startActivity(Intent.FLAG_ACTIVITY_SINGLE_TOP, Bundle()) 165 | startActivity(Bundle()) 166 | 167 | startActivityForResult(100) 168 | startActivityForResult(Bundle(), 100) 169 | startActivityForResult(200, Intent.FLAG_ACTIVITY_CLEAR_TOP) 170 | } 171 | ``` 172 | 173 | #### Easy to Start Service 174 | ```kotlin 175 | // available for Context 176 | fun startServiceExtensions() { 177 | startService() 178 | startService(Bundle()) 179 | } 180 | ``` 181 | 182 | #### Network State 183 | ```kotlin 184 | // available for Context 185 | fun networkExtensions() { 186 | val name = networkTypeName() 187 | val operator = networkOperator() 188 | val type = networkType() 189 | val wifi = isWifi() 190 | val mobile = isMobile() 191 | val connected = isConnected() 192 | } 193 | ``` 194 | 195 | #### Notification Builder 196 | ```kotlin 197 | // available for Context 198 | fun notificationExtensions() { 199 | // easy way using Notification.Builder 200 | val notification = newNotification() { 201 | this.setColor(0x0099cc) 202 | .setAutoCancel(true) 203 | .setContentTitle("Notification Title") 204 | .setContentText("Notification Message Text") 205 | .setDefaults(0) 206 | .setGroup("koi") 207 | .setVibrate(longArrayOf(1, 0, 0, 1)) 208 | .setSubText("this is a sub title") 209 | .setSmallIcon(android.R.drawable.ic_dialog_info) 210 | .setLargeIcon(null) 211 | } 212 | } 213 | ``` 214 | 215 | #### Package Functions 216 | ```kotlin 217 | // available for Context 218 | fun packageExtensions() { 219 | val isYoutubeInstalled = isAppInstalled("com.google.android.youtube") 220 | val isMainProcess = isMainProcess() 221 | val disabled = isComponentDisabled(MainActivity::class.java) 222 | enableComponent(MainActivity::class.java) 223 | 224 | val sig = getPackageSignature() 225 | val sigString = getSignature() 226 | println(dumpSignature()) 227 | } 228 | ``` 229 | 230 | #### System Service 231 | ```kotlin 232 | // available for Context 233 | // easy way to get system service, no cast 234 | fun systemServices() { 235 | val wm = getWindowService() 236 | val tm = getTelephonyManager() 237 | val nm = getNotificationManager() 238 | val cm = getConnectivityManager() 239 | val am = getAccountManager() 240 | val acm = getActivityManager() 241 | val alm = getAlarmManager() 242 | val imm = getInputMethodManager() 243 | val inflater = getLayoutService() 244 | val lm = getLocationManager() 245 | val wifi = getWifiManager() 246 | } 247 | ``` 248 | 249 | #### Easy to Log 250 | ```kotlin 251 | // available for Context 252 | fun logExtensions() { 253 | KoiConfig.logEnabled = true //default is false 254 | // true == Log.VERBOSE 255 | // false == Log.ASSERT 256 | // optional 257 | KoiConfig.logLevel = Log.VERBOSE // default is Log.ASSERT 258 | // 259 | 260 | logv("log functions available in Context") //Log.v 261 | logd("log functions available in Context") //Log.d 262 | loge("log functions available in Context") //Log.e 263 | 264 | // support lazy evaluated message 265 | logv { "lazy eval message lambda" } //Log.v 266 | logw { "lazy eval message lambda" } //Log.w 267 | } 268 | ``` 269 | 270 | ### View Extensions 271 | 272 | #### View Listeners 1 273 | ```kotlin 274 | fun viewListeners1() { 275 | val view = View(this) 276 | // View.OnClickListener 277 | view.onClick { print("view clicked") } 278 | // View.OnLongClickListener 279 | view.onLongClick { print("view long clicked");false } 280 | // View.OnKeyListener 281 | view.onKeyEvent { view, keyCode, event -> 282 | print("keyEvent: action:${event.action} code:$keyCode") 283 | false 284 | } 285 | // View.OnTouchListener 286 | view.onTouchEvent { view, event -> 287 | when (event.actionMasked) { 288 | MotionEvent.ACTION_DOWN -> print("touch down") 289 | MotionEvent.ACTION_UP -> print("touch up") 290 | MotionEvent.ACTION_MOVE -> print("touch move") 291 | } 292 | false 293 | } 294 | // View.OnFocusChangeListener 295 | view.onFocusChange { view, hasFocus -> 296 | print("focus changed = $hasFocus") 297 | } 298 | } 299 | ``` 300 | 301 | #### View Listeners 2 302 | ```kotlin 303 | fun viewListeners2() { 304 | // TextWatcher 305 | val editText = EditText(this) 306 | editText.onTextChange { text, start, before, count -> 307 | print("text changed: $text") 308 | } 309 | 310 | // OnCheckedChangeListener 311 | val checkBox = CheckBox(this) 312 | checkBox.onCheckedChanged { button, isChecked -> 313 | print("CheckBox value changed:$isChecked") 314 | } 315 | 316 | // OnSeekBarChangeListener 317 | val seekBar = SeekBar(this) 318 | seekBar.onProgressChanged { seekBar, progress, fromUser -> 319 | print("seekBar progress: $progress") 320 | } 321 | } 322 | ```` 323 | 324 | #### ListView Listeners 325 | ```kotlin 326 | fun listViewListeners() { 327 | val listView = ListView(this) 328 | // OnItemClickListener 329 | listView.onItemClick { parent, view, position, id -> 330 | print("onItemClick: position=$position") 331 | } 332 | // OnScrollListener 333 | listView.onScrollChanged { view, scrollState -> 334 | print("scroll state changed") 335 | } 336 | } 337 | ``` 338 | 339 | #### View Utils 340 | ```kotlin 341 | // available for View 342 | fun viewSample() { 343 | val w = dm.widthPixels 344 | val h = dm.heightPixels 345 | val v1 = 32.5f 346 | val dp1 = v1.pxToDp() 347 | val v2 = 24f 348 | val px1 = v2.dpToPx() 349 | val dp2 = pxToDp(56) 350 | val px2 = dpToPx(32) 351 | val dp3 = 72.pxToDp() 352 | val px3 = 48.dpToPx() 353 | 354 | hideSoftKeyboard() 355 | val editText = EditText(context) 356 | editText.showSoftKeyboard() 357 | editText.toggleSoftKeyboard() 358 | } 359 | ``` 360 | 361 | ### Adapter Extensions 362 | 363 | #### Easy to Create Adapter 364 | ```kotlin 365 | // easy way to create array adapter 366 | fun adapterFunctions() { 367 | listView.adapter = quickAdapterOf( 368 | android.R.layout.simple_list_item_2, 369 | (1..100).map { "List Item No.$it" }) 370 | { binder, data -> 371 | binder.setText(android.R.id.text1, data) 372 | binder.setText(android.R.id.text2, "Index: ${binder.position}") 373 | } 374 | 375 | val adapter2 = quickAdapterOf(android.R.layout.simple_list_item_1) { 376 | binder, data -> 377 | binder.setText(android.R.id.text1, data) 378 | } 379 | adapter2.addAll(listOf("Cat", "Dog", "Rabbit")) 380 | 381 | val adapter3 = quickAdapterOf(android.R.layout.simple_list_item_1, 382 | arrayOf(1, 2, 3, 4, 5, 6)) { 383 | binder, data -> 384 | binder.setText(android.R.id.text1, "Item Number: $data") 385 | } 386 | 387 | val adapter4 = quickAdapterOf(android.R.layout.simple_list_item_1, 388 | setOf(22, 33, 4, 5, 6, 8, 8, 8)) { 389 | binder, data -> 390 | binder.setText(android.R.id.text1, "Item Number: $data") 391 | } 392 | } 393 | ``` 394 | 395 | ### Bundle Extensions 396 | 397 | #### Bundle Builder 398 | ```kotlin 399 | // available in any where 400 | fun bundleExtension() { 401 | // easy way to create bundle 402 | val bundle = Bundle { 403 | putString("key", "value") 404 | putInt("int", 12345) 405 | putBoolean("boolean", false) 406 | putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5)) 407 | putStringArrayList("strings", arrayListOf("Hello", "World", "Cat")) 408 | } 409 | 410 | // equal to using with 411 | val bundle2 = Bundle() 412 | with(bundle2) { 413 | putString("key", "value") 414 | putInt("int", 12345) 415 | putBoolean("boolean", false) 416 | putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5)) 417 | putStringArrayList("strings", arrayListOf("Hello", "World", "Cat")) 418 | } 419 | } 420 | ``` 421 | 422 | ### Parcelable Extensions 423 | 424 | #### Easy to create Parcelable 425 | ```kotlin 426 | // easy way to create Android Parcelable class 427 | data class Person(val name: String, val age: Int) : Parcelable { 428 | override fun writeToParcel(dest: Parcel, flags: Int) { 429 | dest.writeString(name) 430 | dest.writeInt(age) 431 | } 432 | 433 | override fun describeContents(): Int = 0 434 | protected constructor(p: Parcel) : this(name = p.readString(), age = p.readInt()) {} 435 | companion object { 436 | // using createParcel 437 | @JvmField val CREATOR = createParcel { Person(it) } 438 | } 439 | } 440 | ``` 441 | 442 | ### Collection Extensions 443 | 444 | #### Collection to String 445 | ```kotlin 446 | fun collectionToString() { 447 | val pets = listOf("Cat", "Dog", "Rabbit", "Fish") 448 | // list to string, delimiter is space 449 | val string1 = pets.asString(delim = " ") // "Cat Dog Rabbit Fish" 450 | // default delimiter is comma 451 | val string2 = pets.asString() // "Cat,Dog,Rabbit,Fish" 452 | val numbers = arrayOf(2016, 2, 2, 20, 57, 40) 453 | // array to string, default delimiter is comma 454 | val string3 = numbers.asString() // "2016,2,2,20,57,40" 455 | // array to string, delimiter is - 456 | val string4 = numbers.asString(delim = "-") // 2016-2-2-20-57-40 457 | // using Kotlin stdlib 458 | val s1 = pets.joinToString() 459 | val s2 = numbers.joinToString(separator = "-", prefix = "<", postfix = ">") 460 | } 461 | ``` 462 | 463 | #### Map to String 464 | ```kotlin 465 | fun mapToString() { 466 | val map = mapOf( 467 | "John" to 30, 468 | "Smith" to 50, 469 | "Alice" to 22 470 | ) 471 | // default delimiter is , 472 | val string1 = map.asString() // "John=30,Smith=50,Alice=22" 473 | // using delimiter / 474 | val string2 = map.asString(delim = "/") // "John=30/Smith=50/Alice=22" 475 | // using stdlib 476 | map.asSequence().joinToString { "${it.key}=${it.value}" } 477 | } 478 | ``` 479 | 480 | #### List Append 481 | ```kotlin 482 | fun appendAndPrepend() { 483 | val numbers = (1..6).toArrayList() 484 | println(numbers.joinToString()) // "1, 2, 3, 4, 5, 6, 7" 485 | numbers.head() // .dropLast(1) 486 | numbers.tail() //.drop(1) 487 | val numbers2 = 100.appendTo(numbers) // 488 | val numbers3 = 2016.prependTo(numbers) 489 | } 490 | ``` 491 | 492 | ### Database Extensions 493 | 494 | #### Easy to get Cursor Value 495 | ```kotlin 496 | // available for Cursor 497 | fun cursorValueExtensions() { 498 | val cursor = this.writableDatabase.query("table", null, null, null, null, null, null) 499 | cursor.moveToFirst() 500 | do { 501 | val intVal = cursor.intValue("column-a") 502 | val stringVal = cursor.stringValue("column-b") 503 | val longVal = cursor.longValue("column-c") 504 | val booleanValue = cursor.booleanValue("column-d") 505 | val doubleValue = cursor.doubleValue("column-e") 506 | val floatValue = cursor.floatValue("column-f") 507 | 508 | // no need to do like this, so verbose 509 | cursor.getInt(cursor.getColumnIndexOrThrow("column-a")) 510 | cursor.getString(cursor.getColumnIndexOrThrow("column-b")) 511 | } while (cursor.moveToNext()) 512 | } 513 | ``` 514 | 515 | #### Easy to convert Cursor to Model 516 | ```kotlin 517 | // available for Cursor 518 | // transform cursor to model object 519 | fun cursorToModels() { 520 | val where = " age>? " 521 | val whereArgs = arrayOf("20") 522 | val cursor = this.readableDatabase.query("users", null, where, whereArgs, null, null, null) 523 | val users1 = cursor.map { 524 | UserInfo( 525 | stringValue("name"), 526 | intValue("age"), 527 | stringValue("bio"), 528 | booleanValue("pet_flag")) 529 | } 530 | 531 | // or using mapAndClose 532 | val users2 = cursor.mapAndClose { 533 | UserInfo( 534 | stringValue("name"), 535 | intValue("age"), 536 | stringValue("bio"), 537 | booleanValue("pet_flag")) 538 | } 539 | 540 | // or using Cursor?mapTo(collection, transform()) 541 | } 542 | ``` 543 | 544 | #### Easy to use Transaction 545 | ```kotlin 546 | // available for SQLiteDatabase and SQLiteOpenHelper 547 | // auto apply transaction to db operations 548 | fun inTransaction() { 549 | val db = this.writableDatabase 550 | val values = ContentValues() 551 | 552 | // or db.transaction 553 | transaction { 554 | db.execSQL("insert into users (?,?,?) (1,2,3)") 555 | db.insert("users", null, values) 556 | } 557 | // equal to 558 | db.beginTransaction() 559 | try { 560 | db.execSQL("insert into users (?,?,?) (1,2,3)") 561 | db.insert("users", null, values) 562 | db.setTransactionSuccessful() 563 | } finally { 564 | db.endTransaction() 565 | } 566 | } 567 | ``` 568 | 569 | ### IO Extensions 570 | 571 | #### Easy to close Stream 572 | ```kotlin 573 | // available for Closeable 574 | fun closeableSample() { 575 | val input = FileInputStream(File("readme.txt")) 576 | try { 577 | val string = input.readString("UTF-8") 578 | } catch(e: IOException) { 579 | e.printStackTrace() 580 | } finally { 581 | input.closeQuietly() 582 | } 583 | } 584 | ``` 585 | 586 | #### Stream doSafe Function 587 | ```kotlin 588 | // simple way, equal to closeableSample 589 | // InputStream.doSafe{} 590 | fun doSafeSample() { 591 | val input = FileInputStream(File("readme.txt")) 592 | input.doSafe { 593 | val string = readString("UTF-8") 594 | } 595 | } 596 | ``` 597 | 598 | #### readString/readList 599 | ```kotlin 600 | // available for InputStream/Reader 601 | fun readStringAndList1() { 602 | val input = FileInputStream(File("readme.txt")) 603 | try { 604 | val reader = input.reader(Encoding.CHARSET_UTF_8) 605 | 606 | val string1 = input.readString(Encoding.UTF_8) 607 | val string2 = input.readString(Encoding.CHARSET_UTF_8) 608 | 609 | val list1 = input.readList() 610 | val list2 = input.readList(Encoding.CHARSET_UTF_8) 611 | 612 | } catch(e: IOException) { 613 | 614 | } finally { 615 | input.closeQuietly() 616 | } 617 | } 618 | ``` 619 | 620 | #### readString/readList using doSafe 621 | ```kotlin 622 | // available for InputStream/Reader 623 | //equal to readStringAndList1 624 | fun readStringAndList2() { 625 | val input = FileInputStream(File("readme.txt")) 626 | input.doSafe { 627 | val reader = reader(Encoding.CHARSET_UTF_8) 628 | 629 | val string1 = readString(Encoding.UTF_8) 630 | val string2 = readString(Encoding.CHARSET_UTF_8) 631 | 632 | val list1 = readList() 633 | val list2 = readList(Encoding.CHARSET_UTF_8) 634 | } 635 | } 636 | ``` 637 | 638 | #### writeString/writeList using doSafe 639 | ```kotlin 640 | fun writeStringAndList() { 641 | val output = FileOutputStream("output.txt") 642 | output.doSafe { 643 | output.writeString("hello, world") 644 | output.writeString("Alic's Adventures in Wonderland", charset = Encoding.CHARSET_UTF_8) 645 | 646 | val list1 = listOf(1, 2, 3, 4, 5) 647 | val list2 = (1..8).map { "Item No.$it" } 648 | output.writeList(list1, charset = Encoding.CHARSET_UTF_8) 649 | output.writeList(list2) 650 | } 651 | } 652 | ``` 653 | 654 | #### File Read and Write 655 | ```kotlin 656 | fun fileReadWrite() { 657 | val directory = File("/Users/koi/workspace") 658 | val file = File("some.txt") 659 | 660 | val text1 = file.readText() 661 | val text2 = file.readString(Encoding.CHARSET_UTF_8) 662 | val list1 = file.readList() 663 | val list2 = file.readLines(Encoding.CHARSET_UTF_8) 664 | 665 | file.writeText("hello, world") 666 | file.writeList(list1) 667 | file.writeList(list2, Encoding.CHARSET_UTF_8) 668 | 669 | val v1 = file.relativeToOrNull(directory) 670 | val v2 = file.toRelativeString(directory) 671 | 672 | // clean files in directory 673 | directory.clean() 674 | 675 | 676 | val file1 = File("a.txt") 677 | val file2 = File("b.txt") 678 | file1.copyTo(file2, overwrite = false) 679 | } 680 | ``` 681 | 682 | ### Handler Extensions 683 | 684 | #### Easy to use Handler 685 | ```kotlin 686 | // available for Handler 687 | // short name for functions 688 | fun handlerFunctions() { 689 | val handler = Handler() 690 | handler.atNow { print("perform action now") } 691 | // equal to 692 | handler.post { print("perform action now") } 693 | 694 | handler.atFront { print("perform action at first") } 695 | // equal to 696 | handler.postAtFrontOfQueue { print("perform action at first") } 697 | 698 | handler.atTime(timestamp() + 5000, { print("perform action after 5s") }) 699 | // equal to 700 | handler.postAtTime({ print("perform action after 5s") }, 5000) 701 | 702 | handler.delayed(3000, { print("perform action after 5s") }) 703 | // equal to 704 | handler.postDelayed({ print("perform action after 5s") }, 3000) 705 | } 706 | ``` 707 | 708 | ### Other Extensions 709 | 710 | #### Date Functions 711 | ```kotlin 712 | // available in any where 713 | fun dateSample() { 714 | val nowString = dateNow() 715 | val date = dateParse("2016-02-02 20:30:45") 716 | val dateStr1 = date.asString() 717 | val dateStr2 = date.asString(SimpleDateFormat("yyyyMMdd.HHmmss")) 718 | val dateStr3 = date.asString("yyyy-MM-dd-HH-mm-ss") 719 | 720 | // easy way to get timestamp 721 | val timestamp1 = timestamp() 722 | // equal to 723 | val timestamp2 = System.currentTimeMillis() 724 | val dateStr4 = timestamp1.asDateString() 725 | } 726 | ``` 727 | 728 | #### Number Functions 729 | ```kotlin 730 | fun numberExtensions() { 731 | val number = 179325344324902187L 732 | println(number.readableByteCount()) 733 | 734 | val bytes = byteArrayOf(1, 7, 0, 8, 9, 4, 125) 735 | println(bytes.hexString()) 736 | } 737 | ``` 738 | 739 | #### String Functions 740 | ```kotlin 741 | // available for String 742 | fun stringExtensions() { 743 | val string = "hello, little cat!" 744 | val quotedString = string.quote() 745 | val isBlank = string.isBlank() 746 | val hexBytes = string.toHexBytes() 747 | val s1 = string.trimAllWhitespace() 748 | val c = string.containsWhitespace() 749 | 750 | val url = "https://github.com/mcxiaoke/kotlin-koi?year=2016&encoding=utf8&a=b#changelog" 751 | val urlNoQuery = url.withoutQuery() 752 | 753 | val isNameSafe = url.isNameSafe() 754 | val fileName = url.toSafeFileName() 755 | val queries = url.toQueries() 756 | 757 | val path = "/Users/koi/workspace/String.kt" 758 | val baseName = path.fileNameWithoutExtension() 759 | val extension = path.fileExtension() 760 | val name = path.fileName() 761 | } 762 | ``` 763 | 764 | #### Crypto Functions 765 | ```kotlin 766 | // available in any where 767 | fun cryptoFunctions() { 768 | val md5 = HASH.md5("hello, world") 769 | val sha1 = HASH.sha1("hello, world") 770 | val sha256 = HASH.sha256("hello, world") 771 | } 772 | ``` 773 | 774 | #### Check API Level 775 | ```kotlin 776 | // available in any where 777 | fun apiLevelFunctions() { 778 | // Build.VERSION.SDK_INT 779 | val v = currentVersion() 780 | val ics = icsOrNewer() 781 | val kk = kitkatOrNewer() 782 | val bkk = beforeKitkat() 783 | val lol = lollipopOrNewer() 784 | val mar = marshmallowOrNewer() 785 | } 786 | ``` 787 | 788 | #### Device Functions 789 | ```kotlin 790 | // available in any where 791 | fun deviceSample() { 792 | val a = isLargeHeap 793 | val b = noSdcard() 794 | val c = noFreeSpace(needSize = 10 * 1024 * 1024L) 795 | val d = freeSpace() 796 | } 797 | ``` 798 | 799 | #### Preconditions 800 | ```kotlin 801 | // available in any where 802 | // null and empty check 803 | fun preconditions() { 804 | throwIfEmpty(listOf(), "collection is null or empty") 805 | throwIfNull(null, "object is null") 806 | throwIfTrue(currentVersion() == 10, "result is true") 807 | throwIfFalse(currentVersion() < 4, "result is false") 808 | } 809 | ``` 810 | 811 | ### Thread Functions 812 | 813 | #### Create Thread Pool 814 | ```kotlin 815 | // available in any where 816 | fun executorFunctions() { 817 | // global main handler 818 | val uiHandler1 = CoreExecutor.mainHandler 819 | // or using this function 820 | val uiHandler2 = koiHandler() 821 | 822 | // global executor service 823 | val executor = CoreExecutor.executor 824 | // or using this function 825 | val executor2 = koiExecutor() 826 | 827 | // create thread pool functions 828 | val pool1 = newCachedThreadPool("cached") 829 | val pool2 = newFixedThreadPool("fixed", 4) 830 | val pool3 = newSingleThreadExecutor("single") 831 | } 832 | ``` 833 | 834 | #### Main Thread Functions 835 | ```kotlin 836 | // available in any where 837 | fun mainThreadFunctions() { 838 | //check current thread 839 | // call from any where 840 | val isMain = isMainThread() 841 | 842 | // execute in main thread 843 | mainThread { 844 | print("${(1..8).asSequence().joinToString()}") 845 | } 846 | 847 | // delay execute in main thread 848 | mainThreadDelay(3000) { 849 | print("execute after 3000 ms") 850 | } 851 | } 852 | ``` 853 | 854 | #### Context Check 855 | ```kotlin 856 | 857 | // isContextAlive function impl 858 | fun isContextAlive(context: T?): Boolean { 859 | return when (context) { 860 | null -> false 861 | is Activity -> !context.isFinishing 862 | is Fragment -> context.isAdded 863 | is android.support.v4.app.Fragment -> context.isAdded 864 | is Detachable -> !context.isDetached() 865 | else -> true 866 | } 867 | } 868 | ``` 869 | 870 | #### Safe Functions 871 | ```kotlin 872 | // available in any where 873 | fun safeFunctions() { 874 | val context = this 875 | // check Activity/Fragment lifecycle 876 | val alive = isContextAlive(context) 877 | 878 | fun func1() { 879 | print("func1") 880 | } 881 | // convert to safe function with context check 882 | // internal using isContextAlive 883 | val safeFun1 = safeFunction(::func1) 884 | 885 | // call function with context check 886 | // internal using isContextAlive 887 | safeExecute(::func1) 888 | 889 | // direct use 890 | safeExecute { print("func1") } 891 | } 892 | ``` 893 | 894 | ### Async Functions 895 | 896 | ```kotlin 897 | class AsyncFunctionsSample { 898 | private val intVal = 1000 899 | private var strVal: String? = null 900 | } 901 | ``` 902 | 903 | #### With Context Check 1 904 | ```kotlin 905 | // async functions with context check 906 | // internal using isContextAlive 907 | // context alive: 908 | // !Activity.isFinishing 909 | // Fragment.isAdded 910 | // !Detachable.isDetached 911 | // 912 | // available in any where 913 | // using in Activity/Fragment better 914 | fun asyncSafeFunction1() { 915 | // safe means context alive check 916 | // async 917 | asyncSafe { 918 | print("action executed only if context alive ") 919 | // if you want get caller context 920 | // maybe null 921 | val ctx = getCtx() 922 | // you can also using outside variables 923 | // not recommended 924 | // if context is Activity or Fragment 925 | // may cause memory leak 926 | print("outside value, $intVal $strVal") 927 | 928 | // you can using mainThreadSafe here 929 | // like a callback 930 | mainThreadSafe { 931 | // also with context alive check 932 | // if context dead, not executed 933 | print("code here executed in main thread") 934 | } 935 | // if you don't want context check, using mainThread{} 936 | mainThread { 937 | // no context check 938 | print("code here executed in main thread") 939 | } 940 | } 941 | // if your result or error is nullable 942 | // using asyncSafe2, just as asyncSafe 943 | // but type of result and error is T?, Throwable? 944 | } 945 | ``` 946 | 947 | #### With Context Check 2 948 | ```kotlin 949 | fun asyncSafeFunction2() { 950 | 951 | // async with callback 952 | asyncSafe( 953 | { 954 | print("action executed in async thread") 955 | listOf(1, 2, 3, 4, 5) 956 | }, 957 | { result, error -> 958 | // in main thread 959 | print("callback executed in main thread") 960 | }) 961 | } 962 | ``` 963 | 964 | ```kotlin 965 | fun asyncSafeFunction3() { 966 | // async with success/failure callback 967 | asyncSafe( 968 | { 969 | print("action executed in async thread") 970 | "this string is result of the action" 971 | // throw RuntimeException("action error") 972 | }, 973 | { result -> 974 | // if action success with no exception 975 | print("success callback in main thread result:$result") 976 | }, 977 | { error -> 978 | // if action failed with exception 979 | print("failure callback in main thread, error:$error") 980 | }) 981 | } 982 | ``` 983 | 984 | #### Without Context Check 985 | ```kotlin 986 | // if you don't want context check 987 | // using asyncUnsafe series functions 988 | // just replace asyncSafe with asyncUnsafe 989 | fun asyncUnsafeFunctions() { 990 | // async 991 | asyncUnsafe { 992 | print("action executed with no context check ") 993 | // may cause memory leak 994 | print("outside value, $intVal $strVal") 995 | 996 | mainThread { 997 | // no context check 998 | print("code here executed in main thread") 999 | } 1000 | } 1001 | } 1002 | ``` 1003 | 1004 | #### Custom Executor 1005 | ```kotlin 1006 | val executor = Executors.newFixedThreadPool(4) 1007 | asyncSafe(executor) { 1008 | print("action executed in async thread") 1009 | mainThreadSafe { 1010 | print("code here executed in main thread") 1011 | } 1012 | } 1013 | ``` 1014 | 1015 | #### With Delay 1016 | ```kotlin 1017 | // async functions with delay 1018 | // with context check 1019 | // if context died, not executed 1020 | // others just like asyncSafe 1021 | fun asyncDelayFunctions() { 1022 | // usage see asyncSafe 1023 | asyncDelay(5000) { 1024 | print("action executed after 5000ms only if context alive ") 1025 | 1026 | // you can using mainThreadSafe here 1027 | // like a callback 1028 | mainThreadSafe { 1029 | // also with context alive check 1030 | // if context dead, not executed 1031 | print("code here executed in main thread") 1032 | } 1033 | // if you don't want context check, using mainThread{} 1034 | mainThread { 1035 | // no context check 1036 | print("code here executed in main thread") 1037 | } 1038 | } 1039 | } 1040 | ``` 1041 | 1042 | ### About Me 1043 | 1044 | #### Contacts 1045 | 1046 | * Blog: 1047 | * Github: 1048 | * Email: [github@mcxiaoke.com](mailto:github@mcxiaoke.com) 1049 | 1050 | #### Projects 1051 | 1052 | * awesome-kotlin: 1053 | * Android-Next: 1054 | * PackerNg: 1055 | * gradle-packer-plugin: 1056 | * xBus: 1057 | * ReacitveX Docs: 1058 | * MQTT Translation: 1059 | * Fanfou App: 1060 | * Fanfou Opensource: 1061 | * Volley Mirror: 1062 | 1063 | ------ 1064 | 1065 | ### License 1066 | 1067 | Copyright 2015, 2016 Xiaoke Zhang 1068 | 1069 | Licensed under the Apache License, Version 2.0 (the "License"); 1070 | you may not use this file except in compliance with the License. 1071 | You may obtain a copy of the License at 1072 | 1073 | http://www.apache.org/licenses/LICENSE-2.0 1074 | 1075 | Unless required by applicable law or agreed to in writing, software 1076 | distributed under the License is distributed on an "AS IS" BASIS, 1077 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1078 | See the License for the specific language governing permissions and 1079 | limitations under the License. 1080 | -------------------------------------------------------------------------------- /async/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: '../base.gradle' 2 | apply from: 'https://coding.net/u/mcxiaoke/p/gradle-mvn-push/git/raw/master/gradle-mvn-push.gradle' 3 | 4 | -------------------------------------------------------------------------------- /async/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Koi Library Async Module 2 | POM_ARTIFACT_ID=async 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /async/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /async/src/main/kotlin/com/mcxiaoke/koi/async/Async.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.async 2 | 3 | import android.content.Context 4 | import java.lang.ref.WeakReference 5 | import java.util.concurrent.ExecutorService 6 | import java.util.concurrent.Future 7 | import android.support.v4.app.Fragment as SupportFragment 8 | 9 | /** 10 | * Author: mcxiaoke 11 | * Date: 2016/1/29 8:23 12 | */ 13 | 14 | 15 | //*******************************************************************// 16 | // Extension Async Functions With Context Check 17 | //*******************************************************************// 18 | 19 | inline fun T.asyncSafe( 20 | crossinline action: WeakContext.() -> R): Future { 21 | return asyncSafe(CoreExecutor.executor, action) 22 | } 23 | 24 | inline fun T.asyncSafe( 25 | executor: ExecutorService, 26 | crossinline action: WeakContext.() -> R): Future { 27 | val weakCtx = WeakContext(WeakReference(this)) 28 | return executor.submit { weakCtx.safe { action() } } 29 | } 30 | 31 | fun T.asyncSafe( 32 | action: WeakContext.() -> R, 33 | callback: (result: R?, error: Throwable?) -> Unit): Future { 34 | return asyncSafe(CoreExecutor.executor, action, callback) 35 | } 36 | 37 | fun T.asyncSafe( 38 | executor: ExecutorService, 39 | action: WeakContext.() -> R, 40 | callback: (result: R?, error: Throwable?) -> Unit): Future { 41 | val weakCtx = WeakContext(WeakReference(this)) 42 | return executor.submit { 43 | weakCtx.safe { 44 | try { 45 | val ret = action() 46 | mainThreadSafe { callback(ret, null) } 47 | } catch(ex: Exception) { 48 | mainThreadSafe { callback(null, ex) } 49 | } 50 | } 51 | } 52 | 53 | 54 | } 55 | 56 | inline fun T.asyncSafe( 57 | crossinline action: WeakContext.() -> R, 58 | crossinline success: (result: R) -> Unit, 59 | crossinline failure: (error: Throwable) -> Unit): Future { 60 | return asyncSafe(CoreExecutor.executor, action, success, failure) 61 | } 62 | 63 | inline fun T.asyncSafe( 64 | executor: ExecutorService, 65 | crossinline action: WeakContext.() -> R, 66 | crossinline success: (result: R) -> Unit, 67 | crossinline failure: (error: Throwable) -> Unit): Future { 68 | val weakCtx = WeakContext(WeakReference(this)) 69 | return executor.submit { 70 | weakCtx.safe { 71 | try { 72 | val ret = action() 73 | mainThreadSafe { success(ret) } 74 | } catch(ex: Exception) { 75 | mainThreadSafe { failure(ex) } 76 | } 77 | } 78 | } 79 | } 80 | 81 | 82 | 83 | //*******************************************************************// 84 | // Async Functions Nullable With Context Check 85 | //*******************************************************************// 86 | 87 | inline fun T.asyncSafe2( 88 | crossinline action: WeakContext.() -> R?, 89 | noinline success: ((result: R?) -> Unit)?, 90 | noinline failure: ((error: Throwable?) -> Unit)?): Future { 91 | return asyncSafe2(CoreExecutor.executor, action, success, failure) 92 | } 93 | 94 | inline fun T.asyncSafe2( 95 | executor: ExecutorService, 96 | crossinline action: WeakContext.() -> R?, 97 | noinline success: ((result: R?) -> Unit)?, 98 | noinline failure: ((error: Throwable?) -> Unit)?): Future { 99 | val weakCtx = WeakContext(WeakReference(this)) 100 | return executor.submit { 101 | weakCtx.safe { 102 | try { 103 | val ret = action() 104 | mainThreadSafe { success?.invoke(ret) } 105 | } catch(e: Exception) { 106 | mainThreadSafe { failure?.invoke(e) } 107 | } 108 | } 109 | 110 | } 111 | } 112 | 113 | //*******************************************************************// 114 | // Extension Async Functions With Delay 115 | //*******************************************************************// 116 | 117 | fun T.asyncDelay( 118 | delayInMillis: Long, 119 | action: WeakContext.() -> R): Unit { 120 | asyncDelay(CoreExecutor.executor, delayInMillis, action) 121 | } 122 | 123 | fun T.asyncDelay( 124 | executor: ExecutorService, 125 | delayInMillis: Long, 126 | action: WeakContext.() -> R): Unit { 127 | val weakCtx = WeakContext(WeakReference(this)) 128 | CoreExecutor.mainHandler.postDelayed({ 129 | executor.submit { 130 | weakCtx.safe { action() } 131 | } 132 | }, delayInMillis) 133 | } 134 | 135 | inline fun T.asyncDelay( 136 | delayInMillis: Long, 137 | crossinline action: WeakContext.() -> R?, 138 | crossinline callback: (result: R?) -> Unit): Unit { 139 | return asyncDelay(CoreExecutor.executor, delayInMillis, action, callback) 140 | } 141 | 142 | inline fun T.asyncDelay( 143 | executor: ExecutorService, 144 | delayInMillis: Long, 145 | crossinline action: WeakContext.() -> R?, 146 | crossinline callback: (result: R?) -> Unit): Unit { 147 | val weakCtx = WeakContext(WeakReference(this)) 148 | CoreExecutor.mainHandler.postDelayed({ 149 | executor.submit { 150 | weakCtx.safe { 151 | val ret = action() 152 | mainThreadSafe { callback(ret) } 153 | } 154 | } 155 | }, delayInMillis) 156 | } 157 | 158 | inline fun T.asyncDelay( 159 | delayInMillis: Long, 160 | crossinline action: WeakContext.() -> R?, 161 | crossinline success: (result: R?) -> Unit, 162 | crossinline failure: (error: Throwable) -> Unit): Unit { 163 | return asyncDelay(CoreExecutor.executor, delayInMillis, action, success, failure) 164 | } 165 | 166 | inline fun T.asyncDelay( 167 | executor: ExecutorService, 168 | delayInMillis: Long, 169 | crossinline action: WeakContext.() -> R?, 170 | crossinline success: (result: R?) -> Unit, 171 | crossinline failure: (error: Throwable) -> Unit): Unit { 172 | 173 | val weakCtx = WeakContext(WeakReference(this)) 174 | CoreExecutor.mainHandler.postDelayed({ 175 | executor.submit { 176 | weakCtx.safe { 177 | try { 178 | val ret = action() 179 | mainThreadSafe { success(ret) } 180 | } catch(e: Exception) { 181 | mainThreadSafe { failure(e) } 182 | } 183 | } 184 | } 185 | }, delayInMillis) 186 | } 187 | 188 | //*******************************************************************// 189 | // Extension Async Functions Without Context Check 190 | //*******************************************************************// 191 | 192 | fun T.asyncUnsafe( 193 | action: () -> R?): Future { 194 | return asyncUnsafe(CoreExecutor.executor, action) 195 | } 196 | 197 | fun T.asyncUnsafe( 198 | executor: ExecutorService, 199 | action: () -> R?): Future { 200 | return executor.submit(action) 201 | } 202 | 203 | inline fun T.asyncUnsafe( 204 | crossinline action: () -> R?, 205 | crossinline callback: (result: R?, error: Throwable?) -> Unit): Future { 206 | return asyncUnsafe(CoreExecutor.executor, action, callback) 207 | } 208 | 209 | inline fun T.asyncUnsafe( 210 | executor: ExecutorService, 211 | crossinline action: () -> R?, 212 | crossinline callback: (result: R?, error: Throwable?) -> Unit): Future { 213 | return executor.submit { 214 | try { 215 | val ret = action() 216 | mainThread { callback(ret, null) } 217 | } catch(ex: Exception) { 218 | mainThread { callback(null, ex) } 219 | } 220 | } 221 | } 222 | 223 | inline fun T.asyncUnsafe( 224 | crossinline action: () -> R?, 225 | crossinline success: (result: R?) -> Unit, 226 | crossinline failure: (error: Throwable) -> Unit): Future { 227 | return asyncUnsafe(CoreExecutor.executor, action, success, failure) 228 | } 229 | 230 | inline fun T.asyncUnsafe( 231 | executor: ExecutorService, 232 | crossinline action: () -> R?, 233 | crossinline success: (result: R?) -> Unit, 234 | crossinline failure: (error: Throwable) -> Unit): Future { 235 | return executor.submit { 236 | try { 237 | val ret = action() 238 | mainThread { success(ret) } 239 | } catch(e: Exception) { 240 | mainThread { failure(e) } 241 | } 242 | } 243 | } 244 | 245 | 246 | 247 | -------------------------------------------------------------------------------- /async/src/main/kotlin/com/mcxiaoke/koi/async/Context.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.async 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import android.content.Context 6 | import android.os.Looper 7 | import java.lang.ref.WeakReference 8 | import android.support.v4.app.Fragment as SupportFragment 9 | 10 | /** 11 | * User: mcxiaoke 12 | * Date: 16/1/31 13 | * Time: 14:19 14 | */ 15 | 16 | 17 | interface Detachable { 18 | fun isDetached(): Boolean 19 | } 20 | 21 | class WeakContext(val weakRef: WeakReference) { 22 | private val needCheck: Boolean 23 | 24 | init { 25 | val ctx = weakRef.get() 26 | needCheck = when (ctx) { 27 | is Activity -> true 28 | is Fragment -> true 29 | is SupportFragment -> true 30 | is Detachable -> true 31 | else -> false 32 | } 33 | } 34 | 35 | fun sleep(time: Long) = Thread.sleep(time) 36 | 37 | fun getCtx(): T? = weakRef.get() 38 | 39 | fun isContextAlive(): Boolean { 40 | val context = weakRef.get() ?: return false 41 | return if (needCheck) isContextAlive(context) else true 42 | } 43 | } 44 | 45 | //*******************************************************************// 46 | // Execute Task on Main Thread 47 | //*******************************************************************// 48 | 49 | fun isMainThread(): Boolean = Looper.myLooper() == Looper.getMainLooper() 50 | 51 | fun isContextAlive(context: T?): Boolean { 52 | return when (context) { 53 | null -> false 54 | is Activity -> !context.isFinishing 55 | is Fragment -> context.isAdded 56 | is SupportFragment -> context.isAdded 57 | is Detachable -> !context.isDetached() 58 | else -> true 59 | } 60 | } 61 | 62 | inline fun T.safeFunction( 63 | crossinline action: () -> Unit): 64 | () -> Unit { 65 | return { safeExecute(action) } 66 | } 67 | 68 | inline fun T.safeExecute( 69 | crossinline action: () -> Unit) { 70 | if (isContextAlive(this)) { 71 | action() 72 | } 73 | } 74 | 75 | fun mainThreadDelay(delayMillis: Long, action: () -> Unit): Boolean 76 | = CoreExecutor.mainHandler.postDelayed(action, delayMillis) 77 | 78 | inline fun mainThread(crossinline action: () -> Unit) { 79 | when { 80 | isMainThread() -> action() 81 | else -> CoreExecutor.mainHandler.post { action() } 82 | } 83 | } 84 | 85 | inline fun WeakContext.mainThread(crossinline action: (T) -> Unit) { 86 | val context = weakRef.get() ?: return 87 | when { 88 | isMainThread() -> action(context) 89 | else -> CoreExecutor.mainHandler.post { action(context) } 90 | } 91 | } 92 | 93 | inline fun WeakContext.safe( 94 | crossinline action: WeakContext.(T) -> Unit) { 95 | val context = weakRef.get() ?: return 96 | if (isContextAlive()) { 97 | action(context) 98 | } 99 | } 100 | 101 | inline fun WeakContext.mainThreadSafe( 102 | crossinline action: (T) -> Unit) { 103 | val context = weakRef.get() ?: return 104 | if (isContextAlive()) { 105 | mainThread { action(context) } 106 | } 107 | } 108 | 109 | //fun Context.mainThreadSafe(action: Context.() -> Unit) { 110 | // WeakContext(WeakReference(this)).mainThreadSafe(action) 111 | //} 112 | // 113 | //inline fun Fragment.mainThreadSafe(crossinline action: () -> Unit) { 114 | // activity.mainThreadSafe { action() } 115 | //} 116 | // 117 | //inline fun SupportFragment.mainThreadSafe(crossinline action: () -> Unit) { 118 | // activity.mainThreadSafe { action() } 119 | //} 120 | 121 | -------------------------------------------------------------------------------- /async/src/main/kotlin/com/mcxiaoke/koi/async/Executor.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.async 2 | 3 | import android.os.Handler 4 | import android.os.HandlerThread 5 | import android.os.Looper 6 | import java.util.concurrent.ExecutorService 7 | import java.util.concurrent.Future 8 | 9 | /** 10 | * User: mcxiaoke 11 | * Date: 16/1/31 12 | * Time: 14:20 13 | */ 14 | object CoreExecutor { 15 | private var thread: HandlerThread? = null 16 | 17 | fun quitHandlerThread() { 18 | thread?.quit() 19 | } 20 | 21 | val mainHandler: Handler by lazy { 22 | Handler(Looper.getMainLooper()) 23 | } 24 | 25 | val executor: ExecutorService by lazy { 26 | newCachedThreadPool("koi-core") 27 | } 28 | 29 | fun execute(task: () -> Unit): Future { 30 | return executor.submit { task() } 31 | } 32 | 33 | fun submit(task: () -> T): Future { 34 | return executor.submit(task) 35 | } 36 | } 37 | 38 | fun koiHandler(): Handler = CoreExecutor.mainHandler 39 | fun koiExecutor(): ExecutorService = CoreExecutor.executor 40 | 41 | 42 | -------------------------------------------------------------------------------- /async/src/main/kotlin/com/mcxiaoke/koi/async/Thread.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.async 2 | 3 | import java.util.concurrent.* 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/27 8 | * Time: 11:05 9 | */ 10 | 11 | class CounterThreadFactory(name: String?) : ThreadFactory { 12 | private var count: Int = 0 13 | private val name: String = name ?: "koi" 14 | 15 | override fun newThread(r: Runnable): Thread { 16 | val thread = Thread(r) 17 | thread.name = name + "-thread-" + count++ 18 | return thread 19 | } 20 | } 21 | 22 | fun newCachedThreadPool(name: String): ThreadPoolExecutor { 23 | return ThreadPoolExecutor(0, Integer.MAX_VALUE, 24 | 60L, TimeUnit.SECONDS, 25 | SynchronousQueue(), 26 | CounterThreadFactory(name)) 27 | } 28 | 29 | fun newFixedThreadPool(name: String, nThreads: Int): ThreadPoolExecutor { 30 | return ThreadPoolExecutor(nThreads, nThreads, 31 | 0L, TimeUnit.MILLISECONDS, 32 | LinkedBlockingQueue(), 33 | CounterThreadFactory(name)) 34 | } 35 | 36 | fun newSingleThreadExecutor(name: String): ThreadPoolExecutor { 37 | return newFixedThreadPool(name, 1) 38 | } 39 | -------------------------------------------------------------------------------- /base.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | 4 | dependencies { 5 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 6 | compile "com.android.support:support-v4:$supportVersion" 7 | testCompile "junit:junit:4.12" 8 | testCompile "org.mockito:mockito-core:1.10.19" 9 | } 10 | 11 | android { 12 | compileSdkVersion rootProject.ext.compileSdkVersion 13 | buildToolsVersion rootProject.ext.buildToolsVersion 14 | 15 | defaultConfig { 16 | minSdkVersion rootProject.ext.minSdkVersion 17 | targetSdkVersion rootProject.ext.targetSdkVersion 18 | } 19 | 20 | sourceSets { 21 | main.java.srcDirs += 'src/main/kotlin' 22 | androidTest.java.srcDirs += 'src/androidTest/kotlin' 23 | } 24 | 25 | lintOptions { 26 | quiet true 27 | abortOnError false 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | compileSdkVersion = 25 3 | buildToolsVersion = "25.0.3" 4 | minSdkVersion = 14 5 | targetSdkVersion = 22 6 | } 7 | 8 | buildscript { 9 | ext.kotlinVersion = '1.1.4' 10 | ext.supportVersion = '25.3.1' 11 | 12 | repositories { 13 | jcenter() 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | classpath 'com.android.tools.build:gradle:2.3.3' 19 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 20 | } 21 | } 22 | 23 | allprojects { 24 | 25 | repositories { 26 | mavenLocal() 27 | jcenter() 28 | mavenCentral() 29 | } 30 | 31 | tasks.withType(JavaCompile) { 32 | options.encoding = 'UTF-8' 33 | } 34 | } 35 | 36 | -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: '../base.gradle' 2 | apply from: 'https://coding.net/u/mcxiaoke/p/gradle-mvn-push/git/raw/master/gradle-mvn-push.gradle' 3 | 4 | -------------------------------------------------------------------------------- /core/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Koi Library Core Module 2 | POM_ARTIFACT_ID=core 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /core/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/Constants.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi 2 | 3 | import java.nio.charset.Charset 4 | import java.util.regex.Pattern 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/26 9 | * Time: 16:50 10 | */ 11 | 12 | 13 | object Encoding { 14 | 15 | const val ISO_8859_1 = "ISO-8859-1" 16 | const val US_ASCII = "US-ASCII" 17 | const val UTF_16 = "UTF-16" 18 | const val UTF_16BE = "UTF-16BE" 19 | const val UTF_16LE = "UTF-16LE" 20 | const val UTF_8 = "UTF-8" 21 | val CHARSET_ISO_8859_1: Charset = Charset.forName(ISO_8859_1) 22 | val CHARSET_US_ASCII: Charset = Charset.forName(US_ASCII) 23 | val CHARSET_UTF_16: Charset = Charset.forName(UTF_16) 24 | val CHARSET_UTF_16BE: Charset = Charset.forName(UTF_16BE) 25 | val CHARSET_UTF_16LE: Charset = Charset.forName(UTF_16LE) 26 | val CHARSET_UTF_8: Charset = Charset.forName(UTF_8) 27 | } 28 | 29 | object Const { 30 | const val FILENAME_NOMEDIA = ".nomedia" 31 | const val HEAP_SIZE_LARGE = 48 * 1024 * 1024 32 | const val LINE_SEPARATOR = "\n" 33 | const val FILE_EXTENSION_SEPARATOR = "." 34 | const val RESERVED_CHARS = "|\\?*<\":>+[]/'" 35 | @JvmField val HEX_DIGITS = "0123456789ABCDEF".toCharArray() 36 | @JvmField val SAFE_FILENAME_PATTERN: Pattern = Pattern.compile("[\\w%+,./=_-]+") 37 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/Core.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi 2 | 3 | import android.util.Log 4 | import android.support.v4.app.Fragment as SupportFragment 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/26 9 | * Time: 17:07 10 | */ 11 | 12 | class KoiConfig { 13 | companion object { 14 | var logLevel = Log.ASSERT 15 | var logEnabled: Boolean 16 | get() { 17 | return logLevel < Log.ASSERT 18 | } 19 | set(value) { 20 | logLevel = if (value) Log.VERBOSE else Log.ASSERT 21 | } 22 | } 23 | } 24 | 25 | 26 | fun threadName(): String = Thread.currentThread().name 27 | 28 | inline fun doIf(condition: Boolean?, action: () -> Unit) { 29 | if (condition == true) action() 30 | } 31 | 32 | inline fun doIf(condition: () -> Boolean?, action: () -> Unit) { 33 | if (condition() == true ) action() 34 | } 35 | 36 | inline fun doIf(any: Any?, action: () -> Unit) { 37 | if (any != null ) action() 38 | } 39 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/Crypto.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi 2 | 3 | import android.util.Base64 4 | import java.io.UnsupportedEncodingException 5 | import java.security.MessageDigest 6 | import java.security.NoSuchAlgorithmException 7 | import java.security.SecureRandom 8 | 9 | /** 10 | * @author mcxiaoke 11 | * * 12 | * @version 1.0 2013.03.16 13 | */ 14 | 15 | 16 | private object Helper { 17 | 18 | fun getRandomString(): String = SecureRandom().nextLong().toString() 19 | 20 | fun getRandomBytes(size: Int): ByteArray { 21 | val random = SecureRandom() 22 | val bytes = ByteArray(size) 23 | random.nextBytes(bytes) 24 | return bytes 25 | } 26 | 27 | fun getRawBytes(text: String): ByteArray { 28 | try { 29 | return text.toByteArray(Charsets.UTF_8) 30 | } catch (e: UnsupportedEncodingException) { 31 | return text.toByteArray() 32 | } 33 | } 34 | 35 | fun getString(data: ByteArray): String { 36 | try { 37 | return String(data, Charsets.UTF_8) 38 | } catch (e: UnsupportedEncodingException) { 39 | return String(data) 40 | } 41 | 42 | } 43 | 44 | fun base64Decode(text: String): ByteArray { 45 | return Base64.decode(text, Base64.NO_WRAP) 46 | } 47 | 48 | fun base64Encode(data: ByteArray): String { 49 | return Base64.encodeToString(data, Base64.NO_WRAP) 50 | } 51 | } 52 | 53 | object HASH { 54 | private val MD5 = "MD5" 55 | private val SHA_1 = "SHA-1" 56 | private val SHA_256 = "SHA-256" 57 | private val DIGITS_LOWER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') 58 | private val DIGITS_UPPER = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') 59 | 60 | fun md5(data: ByteArray): String { 61 | return String(encodeHex(md5Bytes(data))) 62 | } 63 | 64 | fun md5(text: String): String { 65 | return String(encodeHex(md5Bytes(Helper.getRawBytes(text)))) 66 | } 67 | 68 | fun md5Bytes(data: ByteArray): ByteArray { 69 | return getDigest(MD5).digest(data) 70 | } 71 | 72 | fun sha1(data: ByteArray): String { 73 | return String(encodeHex(sha1Bytes(data))) 74 | } 75 | 76 | fun sha1(text: String): String { 77 | return String(encodeHex(sha1Bytes(Helper.getRawBytes(text)))) 78 | } 79 | 80 | fun sha1Bytes(data: ByteArray): ByteArray { 81 | return getDigest(SHA_1).digest(data) 82 | } 83 | 84 | fun sha256(data: ByteArray): String { 85 | return String(encodeHex(sha256Bytes(data))) 86 | } 87 | 88 | fun sha256(text: String): String { 89 | return String(encodeHex(sha256Bytes(Helper.getRawBytes(text)))) 90 | } 91 | 92 | fun sha256Bytes(data: ByteArray): ByteArray { 93 | return getDigest(SHA_256).digest(data) 94 | } 95 | 96 | fun getDigest(algorithm: String): MessageDigest { 97 | try { 98 | return MessageDigest.getInstance(algorithm) 99 | } catch (e: NoSuchAlgorithmException) { 100 | throw IllegalArgumentException(e) 101 | } 102 | 103 | } 104 | 105 | fun encodeHex(data: ByteArray, toLowerCase: Boolean = true): CharArray { 106 | return encodeHex(data, if (toLowerCase) DIGITS_LOWER else DIGITS_UPPER) 107 | } 108 | 109 | fun encodeHex(data: ByteArray, toDigits: CharArray): CharArray { 110 | val l = data.size 111 | val out = CharArray(l shl 1) 112 | var i = 0 113 | var j = 0 114 | while (i < l) { 115 | out[j++] = toDigits[(240 and data[i].toInt()).ushr(4)] 116 | out[j++] = toDigits[15 and data[i].toInt()] 117 | i++ 118 | } 119 | return out 120 | } 121 | 122 | } 123 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/adapter/ArrayAdapterEx.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.adapter 2 | 3 | import android.content.Context 4 | import android.content.res.Resources 5 | import android.view.LayoutInflater 6 | import android.view.View 7 | import android.view.ViewGroup 8 | import android.widget.BaseAdapter 9 | import java.util.Comparator 10 | 11 | /** 12 | * 从系统源码复制出来,精简了一些无用的方法,添加了一些实用的方法 13 | * public List getAllItems() //获取Adapter里所有的数据项 14 | * public void add(int index, T object) // 指定位置插入数据 15 | * public void set(int index, T object) // 指定位置插入数据 16 | * public void addAll(int index, Collection collection) //指定位置批量插入数据 17 | * public void addAll(int index, T... items) //指定位置批量插入数据 18 | * public boolean contains(T object) //是否包含某个数据项 19 | * public int indexOf(T object) // 同上,返回index,不包含就返回-1 20 | * public void removeAt(int index) // 移除某个位置的数据项 21 | 22 | * @param 23 | */ 24 | 25 | /** 26 | * User: mcxiaoke 27 | * Date: 16/1/30 28 | * Time: 18:21 29 | */ 30 | abstract class ArrayAdapterEx( 31 | protected val context: Context, 32 | protected val objects: MutableList) 33 | : BaseAdapter() { 34 | 35 | private val lock = Object() 36 | protected val inflater: LayoutInflater = LayoutInflater.from(context) 37 | protected val resources: Resources = context.resources 38 | 39 | var notifyChange = true 40 | 41 | constructor(context: Context) 42 | : this(context, arrayListOf()) 43 | 44 | constructor(context: Context, objects: Array) 45 | : this(context, objects.toMutableList()) 46 | 47 | constructor(context: Context, objects: Collection) 48 | : this(context, objects.toMutableList()) 49 | 50 | fun addAll(items: Collection): ArrayAdapterEx { 51 | synchronized (lock) { 52 | objects.addAll(items) 53 | } 54 | if (notifyChange) { 55 | notifyDataSetChanged() 56 | } 57 | return this 58 | } 59 | 60 | fun addAll(index: Int, collection: Collection): ArrayAdapterEx { 61 | synchronized (lock) { 62 | objects.addAll(index, collection) 63 | } 64 | if (notifyChange) { 65 | notifyDataSetChanged() 66 | } 67 | return this 68 | } 69 | 70 | fun removeAll(items: Collection): Boolean { 71 | var result = false 72 | synchronized (lock) { 73 | result = objects.removeAll(items) 74 | } 75 | if (notifyChange) { 76 | notifyDataSetChanged() 77 | } 78 | return result 79 | } 80 | 81 | fun clear(): ArrayAdapterEx { 82 | synchronized (lock) { 83 | objects.clear() 84 | } 85 | if (notifyChange) { 86 | notifyDataSetChanged() 87 | } 88 | return this 89 | } 90 | 91 | fun sort(comparator: Comparator): ArrayAdapterEx { 92 | synchronized (lock) { 93 | objects.sortWith(comparator) 94 | } 95 | if (notifyChange) { 96 | notifyDataSetChanged() 97 | } 98 | return this 99 | } 100 | 101 | fun allItems(): List { 102 | return objects 103 | } 104 | 105 | 106 | fun add(newItem: T): ArrayAdapterEx { 107 | synchronized (lock) { 108 | objects.add(newItem) 109 | } 110 | if (notifyChange) { 111 | notifyDataSetChanged() 112 | } 113 | return this 114 | } 115 | 116 | fun add(index: Int, newItem: T): ArrayAdapterEx { 117 | synchronized (lock) { 118 | objects.add(index, newItem) 119 | } 120 | if (notifyChange) { 121 | notifyDataSetChanged() 122 | } 123 | return this 124 | } 125 | 126 | operator fun set(index: Int, newItem: T): ArrayAdapterEx { 127 | synchronized (lock) { 128 | objects.set(index, newItem) 129 | } 130 | if (notifyChange) { 131 | notifyDataSetChanged() 132 | } 133 | return this 134 | } 135 | 136 | operator fun contains(newItem: T): Boolean { 137 | synchronized (lock) { 138 | return objects.contains(newItem) 139 | } 140 | } 141 | 142 | fun indexOf(newItem: T): Int { 143 | synchronized (lock) { 144 | return objects.indexOf(newItem) 145 | } 146 | } 147 | 148 | fun remove(newItem: T) { 149 | synchronized (lock) { 150 | objects.remove(newItem) 151 | } 152 | if (notifyChange) { 153 | notifyDataSetChanged() 154 | } 155 | } 156 | 157 | fun removeAt(index: Int) { 158 | synchronized (lock) { 159 | objects.removeAt(index) 160 | } 161 | if (notifyChange) { 162 | notifyDataSetChanged() 163 | } 164 | } 165 | 166 | fun getPosition(item: T): Int { 167 | return objects.indexOf(item) 168 | } 169 | 170 | fun lastOrNull(): T? { 171 | return objects.lastOrNull() 172 | } 173 | 174 | fun firstOrNull(): T? { 175 | return objects.firstOrNull() 176 | } 177 | 178 | fun getItemOrNull(position: Int): T? { 179 | return objects.getOrNull(position) 180 | } 181 | 182 | override fun getCount(): Int { 183 | return objects.size 184 | } 185 | 186 | override fun getItem(position: Int): T { 187 | return objects[position] 188 | } 189 | 190 | override fun getItemId(position: Int): Long { 191 | return position.toLong() 192 | } 193 | 194 | override fun getView(position: Int, 195 | convertView: View?, 196 | parent: ViewGroup): View? { 197 | val view: View 198 | when (convertView) { 199 | null -> view = newView(position, parent) 200 | else -> view = convertView 201 | } 202 | bindView(position, view) 203 | return view 204 | } 205 | 206 | abstract fun newView(position: Int, parent: ViewGroup): View 207 | abstract fun bindView(position: Int, view: View) 208 | } 209 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/adapter/QuickAdapter.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.adapter 2 | 3 | import android.content.Context 4 | import android.view.View 5 | import android.view.ViewGroup 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/30 10 | * Time: 18:48 11 | */ 12 | 13 | open class QuickAdapter( 14 | ctx: Context, 15 | protected val layoutId: Int, 16 | protected val bind: (QuickViewBinder, T) -> Unit) 17 | : ArrayAdapterEx(ctx, arrayListOf()) { 18 | 19 | override fun newView(position: Int, parent: ViewGroup): View { 20 | val binder = QuickViewBinder(context, 21 | inflater.inflate(layoutId, parent, false), 22 | position) 23 | return binder.view 24 | } 25 | 26 | override fun bindView(position: Int, view: View) { 27 | val binder = view.tag as QuickViewBinder 28 | binder.position = position 29 | bind(binder, getItem(position)) 30 | } 31 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/adapter/QuickViewBinder.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.adapter 2 | 3 | import android.content.Context 4 | import android.graphics.Bitmap 5 | import android.graphics.drawable.Drawable 6 | import android.text.util.Linkify 7 | import android.view.View 8 | import android.widget.* 9 | 10 | /** 11 | * User: mcxiaoke 12 | * Date: 16/1/30 13 | * Time: 18:57 14 | */ 15 | 16 | open class QuickViewBinder constructor( 17 | val context: Context, 18 | val view: View, 19 | var position: Int) { 20 | 21 | init { 22 | view.tag = this 23 | } 24 | 25 | inline fun findView(viewId: Int): T = view.findViewById(viewId) as T 26 | 27 | fun setText(viewId: Int, value: String): QuickViewBinder { 28 | findView(viewId).text = value 29 | return this 30 | } 31 | 32 | fun setImageResource(viewId: Int, imageResId: Int): QuickViewBinder { 33 | findView(viewId).setImageResource(imageResId) 34 | return this 35 | } 36 | 37 | fun setBackgroundColor(viewId: Int, color: Int): QuickViewBinder { 38 | findView(viewId).setBackgroundColor(color) 39 | return this 40 | } 41 | 42 | fun setBackgroundRes(viewId: Int, backgroundRes: Int): QuickViewBinder { 43 | findView(viewId).setBackgroundResource(backgroundRes) 44 | return this 45 | } 46 | 47 | fun setTextColor(viewId: Int, textColor: Int): QuickViewBinder { 48 | findView(viewId).setTextColor(textColor) 49 | return this 50 | } 51 | 52 | fun setTextColorRes(viewId: Int, textColorRes: Int): QuickViewBinder { 53 | findView(viewId).setTextColor(context.resources.getColor(textColorRes)) 54 | return this 55 | } 56 | 57 | fun setImageDrawable(viewId: Int, drawable: Drawable): QuickViewBinder { 58 | findView(viewId).setImageDrawable(drawable) 59 | return this 60 | } 61 | 62 | fun setImageBitmap(viewId: Int, bitmap: Bitmap): QuickViewBinder { 63 | findView(viewId).setImageBitmap(bitmap) 64 | return this 65 | } 66 | 67 | fun setAlpha(viewId: Int, value: Float): QuickViewBinder { 68 | findView(viewId).alpha = value 69 | return this 70 | } 71 | 72 | fun setVisible(viewId: Int, visible: Boolean): QuickViewBinder { 73 | findView(viewId).visibility = if (visible) View.VISIBLE else View.GONE 74 | return this 75 | } 76 | 77 | fun linkify(viewId: Int): QuickViewBinder { 78 | Linkify.addLinks(findView(viewId), Linkify.ALL) 79 | return this 80 | } 81 | 82 | fun setOnClickListener(viewId: Int, 83 | listener: View.OnClickListener): QuickViewBinder { 84 | findView(viewId).setOnClickListener(listener) 85 | return this 86 | } 87 | 88 | fun setOnTouchListener(viewId: Int, 89 | listener: View.OnTouchListener): QuickViewBinder { 90 | findView(viewId).setOnTouchListener(listener) 91 | return this 92 | } 93 | 94 | fun setOnLongClickListener(viewId: Int, 95 | listener: View.OnLongClickListener) 96 | : QuickViewBinder { 97 | findView(viewId).setOnLongClickListener(listener) 98 | return this 99 | } 100 | 101 | fun setOnItemClickListener(viewId: Int, 102 | listener: AdapterView.OnItemClickListener) 103 | : QuickViewBinder { 104 | findView>(viewId).onItemClickListener = listener 105 | return this 106 | } 107 | 108 | fun setOnItemLongClickListener(viewId: Int, 109 | listener: AdapterView.OnItemLongClickListener) 110 | : QuickViewBinder { 111 | findView>(viewId).onItemLongClickListener = listener 112 | return this 113 | } 114 | 115 | fun setChecked(viewId: Int, checked: Boolean): QuickViewBinder { 116 | (findView(viewId) as Checkable).isChecked = checked 117 | return this 118 | } 119 | 120 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/assert/Preconditions.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.assert 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/26 6 | * Time: 16:50 7 | */ 8 | 9 | 10 | fun throwIfNull(obj: T?, message: String? = "object is null") { 11 | if (obj == null) { 12 | throw IllegalArgumentException(message) 13 | } 14 | } 15 | 16 | fun throwIfEmpty(obj: String?, message: String? = "string is null or empty") { 17 | if (obj == null || obj.isEmpty()) { 18 | throw IllegalArgumentException(message) 19 | } 20 | } 21 | 22 | fun throwIfEmpty(obj: Collection?, message: String? = "collection is null or empty") { 23 | if (obj == null || obj.isEmpty()) { 24 | throw IllegalArgumentException(message) 25 | } 26 | } 27 | 28 | fun throwIfFalse(condition: Boolean, message: String? = "condition is false") { 29 | if (!condition) { 30 | throw IllegalArgumentException(message) 31 | } 32 | } 33 | 34 | fun throwIfTrue(condition: Boolean, message: String? = "condition is true") { 35 | if (condition) { 36 | throw IllegalArgumentException(message) 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Activity.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import android.content.Intent 6 | import android.view.View 7 | import android.support.v4.app.Fragment as SupportFragment 8 | 9 | /** 10 | * User: mcxiaoke 11 | * Date: 16/1/22 12 | * Time: 13:14 13 | */ 14 | 15 | 16 | fun Activity.getActivity(): Activity = this 17 | 18 | fun View.getActivity(): Activity = context as Activity 19 | 20 | fun Fragment.finish() = activity?.finish() 21 | 22 | fun SupportFragment.finish() = activity?.finish() 23 | 24 | fun Activity.restart() { 25 | val intent = this.intent 26 | this.overridePendingTransition(0, 0) 27 | intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) 28 | this.finish() 29 | this.overridePendingTransition(0, 0) 30 | this.startActivity(intent) 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Adapter.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Activity 4 | import com.mcxiaoke.koi.adapter.QuickAdapter 5 | import com.mcxiaoke.koi.adapter.QuickViewBinder 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/31 10 | * Time: 09:34 11 | */ 12 | 13 | fun Activity.quickAdapterOf( 14 | layoutId: Int, 15 | items: Collection, 16 | bind: ((QuickViewBinder, T) -> Unit)) 17 | : QuickAdapter { 18 | val adapter = quickAdapterOf(layoutId, bind) 19 | adapter.addAll(items) 20 | return adapter 21 | } 22 | 23 | fun Activity.quickAdapterOf( 24 | layoutId: Int, 25 | items: Array, 26 | bind: ((QuickViewBinder, T) -> Unit)) 27 | : QuickAdapter { 28 | val adapter = quickAdapterOf(layoutId, bind) 29 | adapter.addAll(items.toList()) 30 | return adapter 31 | } 32 | 33 | fun Activity.quickAdapterOf( 34 | layoutId: Int, 35 | items: Set, 36 | bind: ((QuickViewBinder, T) -> Unit)) 37 | : QuickAdapter { 38 | val adapter = quickAdapterOf(layoutId, bind) 39 | adapter.addAll(items) 40 | return adapter 41 | } 42 | 43 | fun Activity.quickAdapterOf( 44 | layoutId: Int, 45 | bind: ((QuickViewBinder, T) -> Unit)) 46 | : QuickAdapter { 47 | return QuickAdapter(this, layoutId, bind) 48 | } 49 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Application.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Activity 4 | import android.app.Application 5 | import android.app.Fragment 6 | import android.app.Service 7 | import android.view.View 8 | import android.support.v4.app.Fragment as SupportFragment 9 | 10 | /** 11 | * User: mcxiaoke 12 | * Date: 16/1/31 13 | * Time: 10:30 14 | */ 15 | 16 | fun Activity.getApp(): Application = application 17 | 18 | fun Service.getApp(): Application = application 19 | 20 | fun View.getApp(): Application = context.applicationContext as Application 21 | 22 | fun Fragment.getApp(): Application = activity.application 23 | 24 | fun SupportFragment.getApp(): Application = activity.application 25 | 26 | 27 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Bundle.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.os.Bundle 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/26 8 | * Time: 16:43 9 | */ 10 | 11 | inline fun Bundle(body: Bundle.() -> Unit): Bundle { 12 | val bundle = Bundle() 13 | bundle.body() 14 | return bundle 15 | } 16 | 17 | inline fun Bundle(loader: ClassLoader, body: Bundle.() -> Unit): Bundle { 18 | val bundle = Bundle(loader) 19 | bundle.body() 20 | return bundle 21 | } 22 | 23 | inline fun Bundle(capacity: Int, body: Bundle.() -> Unit): Bundle { 24 | val bundle = Bundle(capacity) 25 | bundle.body() 26 | return bundle 27 | } 28 | 29 | inline fun Bundle(b: Bundle?, body: Bundle.() -> Unit): Bundle { 30 | val bundle = Bundle(b) 31 | bundle.body() 32 | return bundle 33 | } 34 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Collections.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import java.util.* 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/22 8 | * Time: 13:46 9 | */ 10 | 11 | @JvmOverloads fun Array.asString(delim: String = ","): String { 12 | if (this.isEmpty()) { 13 | return "" 14 | } 15 | val sb = StringBuilder() 16 | forEachIndexed { i, t -> 17 | if (i > 0) { 18 | sb.append(delim) 19 | } 20 | sb.append(t) 21 | } 22 | return sb.toString() 23 | } 24 | 25 | @JvmOverloads fun Collection.asString(delim: String = ","): String { 26 | if (this.isEmpty()) { 27 | return "" 28 | } 29 | val sb = StringBuilder() 30 | forEachIndexed { i, t -> 31 | if (i > 0) { 32 | sb.append(delim) 33 | } 34 | sb.append(t) 35 | } 36 | return sb.toString() 37 | } 38 | 39 | @JvmOverloads fun Map.asString(delim: String = ","): String { 40 | if (this.isEmpty()) { 41 | return "" 42 | } 43 | val strings = ArrayList() 44 | for ((k, v) in this) { 45 | strings.add("$k=$v") 46 | } 47 | return strings.asString(delim) 48 | } 49 | 50 | fun List.head(): List { 51 | return this.dropLast(1) 52 | } 53 | 54 | fun List.tail(): List { 55 | return this.drop(1) 56 | } 57 | 58 | infix fun T.appendTo(list: List): List { 59 | return list + listOf(this) 60 | } 61 | 62 | infix fun T.prependTo(list: List): List { 63 | return listOf(this) + list 64 | } 65 | 66 | 67 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Context.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.Activity 5 | import android.app.Fragment 6 | import android.app.Notification 7 | import android.content.* 8 | import android.content.pm.PackageManager 9 | import android.database.Cursor 10 | import android.media.MediaScannerConnection 11 | import android.net.Uri 12 | import android.os.Build 13 | import android.os.Environment 14 | import android.provider.DocumentsContract 15 | import android.provider.MediaStore 16 | import android.support.v4.app.NotificationCompat 17 | import android.util.DisplayMetrics 18 | import android.util.TypedValue 19 | import android.view.LayoutInflater 20 | import android.view.View 21 | import android.view.ViewGroup 22 | import com.mcxiaoke.koi.Const 23 | import java.io.File 24 | import java.io.IOException 25 | 26 | /** 27 | * User: mcxiaoke 28 | * Date: 16/1/22 29 | * Time: 13:09 30 | */ 31 | 32 | 33 | val Context.inflater: LayoutInflater 34 | get() = LayoutInflater.from(this) 35 | 36 | val Context.displayMetrics: DisplayMetrics 37 | get() = resources.displayMetrics 38 | 39 | 40 | fun Context.dpToPx(dp: Int): Int { 41 | return (dp * this.displayMetrics.density + 0.5).toInt() 42 | } 43 | 44 | fun Context.pxToDp(px: Int): Int { 45 | return (px / this.displayMetrics.density + 0.5).toInt() 46 | } 47 | 48 | inline fun View.find(id: Int): T = this.findViewById(id) as T 49 | 50 | inline fun Activity.find(id: Int): T = this.findViewById(id) as T 51 | 52 | inline fun Fragment.find(id: Int): T = this.view.findViewById(id) as T 53 | 54 | private fun inflateView(context: Context, layoutResId: Int, parent: ViewGroup?, 55 | attachToRoot: Boolean): View = 56 | LayoutInflater.from(context).inflate(layoutResId, parent, attachToRoot) 57 | 58 | fun Context.inflate(layoutResId: Int): View = 59 | inflateView(this, layoutResId, null, false) 60 | 61 | fun Context.inflate(layoutResId: Int, parent: ViewGroup): View = 62 | inflate(layoutResId, parent, true) 63 | 64 | fun Context.inflate(layoutResId: Int, parent: ViewGroup, attachToRoot: Boolean): View = 65 | inflateView(this, layoutResId, parent, attachToRoot) 66 | 67 | fun Context.hasCamera(): Boolean { 68 | val pm = this.packageManager 69 | return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) 70 | || pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) 71 | } 72 | 73 | fun Context.mediaScan(uri: Uri) { 74 | val intent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) 75 | intent.data = uri 76 | this.sendBroadcast(intent) 77 | } 78 | 79 | // another media scan way 80 | fun Context.addToMediaStore(file: File) { 81 | val path = arrayOf(file.path) 82 | MediaScannerConnection.scanFile(this, path, null, null) 83 | } 84 | 85 | fun Context.getBatteryStatus(): Intent { 86 | val appContext = this.applicationContext 87 | return appContext.registerReceiver(null, 88 | IntentFilter(Intent.ACTION_BATTERY_CHANGED)) 89 | } 90 | 91 | fun Context.getResourceValue(resId: Int): Int { 92 | val value = TypedValue() 93 | this.resources.getValue(resId, value, true) 94 | return TypedValue.complexToFloat(value.data).toInt() 95 | } 96 | 97 | inline fun Context.newNotification(func: NotificationCompat.Builder.() -> Unit): Notification { 98 | val builder = NotificationCompat.Builder(this) 99 | builder.func() 100 | return builder.build() 101 | } 102 | 103 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Cursor.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.database.Cursor 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/26 8 | * Time: 16:57 9 | */ 10 | fun Cursor.intValue(columnName: String): Int { 11 | return getInt(getColumnIndexOrThrow(columnName)) 12 | } 13 | 14 | fun Cursor.shortValue(columnName: String): Short { 15 | return getShort(getColumnIndexOrThrow(columnName)) 16 | } 17 | 18 | fun Cursor.longValue(columnName: String): Long { 19 | return getLong(getColumnIndexOrThrow(columnName)) 20 | } 21 | 22 | fun Cursor.doubleValue(columnName: String): Double { 23 | return getDouble(getColumnIndexOrThrow(columnName)) 24 | } 25 | 26 | fun Cursor.floatValue(columnName: String): Float { 27 | return getFloat(getColumnIndexOrThrow(columnName)) 28 | } 29 | 30 | 31 | fun Cursor.stringValue(columnName: String): String { 32 | return getString(getColumnIndexOrThrow(columnName)) 33 | } 34 | 35 | fun Cursor.booleanValue(columnName: String): Boolean { 36 | return getInt(getColumnIndexOrThrow(columnName)) != 0 37 | } 38 | 39 | inline fun Cursor?.map(transform: Cursor.() -> T): MutableCollection { 40 | return mapTo(arrayListOf(), transform) 41 | } 42 | 43 | inline fun > Cursor?.mapTo(result: R, transform: Cursor.() -> T): R { 44 | return if (this == null) result else { 45 | if (moveToFirst()) 46 | do { 47 | result.add(transform()) 48 | } while (moveToNext()) 49 | result 50 | } 51 | } 52 | 53 | inline fun Cursor?.mapAndClose(transform: Cursor.() -> T): MutableCollection { 54 | this.use { 55 | return map(transform) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Database.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.database.sqlite.SQLiteDatabase 4 | import android.database.sqlite.SQLiteOpenHelper 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/30 9 | * Time: 00:23 10 | */ 11 | 12 | inline fun SQLiteOpenHelper.transaction(action: SQLiteDatabase.() -> Unit) { 13 | writableDatabase.transaction(action) 14 | } 15 | 16 | inline fun SQLiteDatabase.transaction(action: SQLiteDatabase.() -> Unit) { 17 | beginTransaction() 18 | try { 19 | action(this) 20 | setTransactionSuccessful() 21 | } finally { 22 | endTransaction() 23 | } 24 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Date.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import java.text.DateFormat 4 | import java.text.ParsePosition 5 | import java.text.SimpleDateFormat 6 | import java.util.* 7 | 8 | /** 9 | * User: mcxiaoke 10 | * Date: 16/1/30 11 | * Time: 00:22 12 | */ 13 | object DateHelper { 14 | const val DF_SIMPLE_STRING = "yyyy-MM-dd HH:mm:ss" 15 | @JvmField val DF_SIMPLE_FORMAT = object : ThreadLocal() { 16 | override fun initialValue(): DateFormat { 17 | return SimpleDateFormat(DF_SIMPLE_STRING, Locale.US) 18 | } 19 | } 20 | } 21 | 22 | fun dateNow(): String = Date().asString() 23 | 24 | fun timestamp(): Long = System.currentTimeMillis() 25 | 26 | fun dateParse(s: String): Date = DateHelper.DF_SIMPLE_FORMAT.get().parse(s, ParsePosition(0)) 27 | 28 | fun Date.asString(format: DateFormat): String = format.format(this) 29 | 30 | fun Date.asString(format: String): String = asString(SimpleDateFormat(format, Locale.US)) 31 | 32 | fun Date.asString(): String = DateHelper.DF_SIMPLE_FORMAT.get().format(this) 33 | 34 | fun Long.asDateString(): String = Date(this).asString() 35 | 36 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Functions.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/30 6 | * Time: 11:36 7 | */ 8 | 9 | infix fun Function1.andThen(f: (IP) -> R): (P1) -> R = forwardCompose(f) 10 | 11 | infix fun Function1.forwardCompose(f: (IP) -> R): (P1) -> R { 12 | return { p1: P1 -> f(this(p1)) } 13 | } 14 | 15 | infix fun Function1.compose(f: (P1) -> IP): (P1) -> R { 16 | return { p1: P1 -> this(f(p1)) } 17 | } 18 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Handler.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.os.Handler 4 | import android.os.Message 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/26 9 | * Time: 17:58 10 | */ 11 | inline fun Handler.atNow(crossinline action: () -> T): Boolean 12 | = post({ action() }) 13 | 14 | inline fun Handler.atFront(crossinline action: () -> T): Boolean 15 | = postAtFrontOfQueue({ action() }) 16 | 17 | inline fun Handler.atTime(uptimeMillis: Long, crossinline action: () -> T): Boolean 18 | = postAtTime({ action() }, uptimeMillis) 19 | 20 | inline fun Handler.delayed(delayMillis: Long, crossinline action: () -> T): Boolean 21 | = postDelayed({ action() }, delayMillis) 22 | 23 | inline fun Handler.repeat(delayMillis: Long, startDelayMillis: Long = 0, repeatCount: Int = 0, crossinline action: (Int) -> T) { 24 | if (startDelayMillis < 0) throw IllegalArgumentException("Start delay must be a positive Int or 0") 25 | if (repeatCount < 0) throw IllegalArgumentException("Repeat count must be a positive Int or 0") 26 | var counter = 0 27 | postDelayed(object : Runnable { 28 | override fun run() { 29 | action(counter ++) 30 | if (repeatCount == 0 || counter < repeatCount) postDelayed(this, delayMillis) 31 | } 32 | }, startDelayMillis) 33 | } 34 | 35 | fun Handler.cancelAll() = removeCallbacksAndMessages(null) 36 | 37 | fun handler(handleMessage: (Message) -> Boolean): Handler { 38 | return Handler { p -> if (p == null) false else handleMessage(p) } 39 | } 40 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/IO.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import com.mcxiaoke.koi.Const 4 | import com.mcxiaoke.koi.Encoding 5 | import java.io.* 6 | import java.net.HttpURLConnection 7 | import java.net.URLConnection 8 | import java.nio.channels.FileChannel 9 | import java.nio.charset.Charset 10 | 11 | /** 12 | * User: mcxiaoke 13 | * Date: 16/1/22 14 | * Time: 14:48 15 | */ 16 | 17 | fun T.doSafe(action: T.() -> Unit) { 18 | try { 19 | action() 20 | } catch(e: IOException) { 21 | } finally { 22 | closeQuietly() 23 | } 24 | } 25 | 26 | fun T?.closeQuietly() { 27 | try { 28 | this?.close() 29 | } catch (ignored: IOException) { 30 | // ignore 31 | } 32 | } 33 | 34 | fun URLConnection.close() { 35 | if (this is HttpURLConnection) { 36 | this.disconnect() 37 | } 38 | } 39 | 40 | @Throws(IOException::class) 41 | fun Reader.readString(): String { 42 | val buffer = charArrayOf() 43 | this.read(buffer) 44 | return String(buffer) 45 | } 46 | 47 | @Throws(IOException::class) 48 | @JvmOverloads fun InputStream.readString(charset: Charset = Charsets.UTF_8): String { 49 | val buffer = charArrayOf() 50 | this.reader(charset).read(buffer) 51 | return String(buffer) 52 | } 53 | 54 | @Throws(IOException::class) 55 | @JvmOverloads fun File.readString(charset: Charset = Charsets.UTF_8): String { 56 | val input = FileInputStream(this) 57 | return input.readString(charset) 58 | } 59 | 60 | @Throws(IOException::class) 61 | fun Reader.readList(): List { 62 | return BufferedReader(this).lineSequence().toList() 63 | } 64 | 65 | @Throws(IOException::class) 66 | @JvmOverloads fun InputStream.readList(charset: Charset = Charsets.UTF_8): List { 67 | return this.reader(charset).readList() 68 | } 69 | 70 | @Throws(IOException::class) 71 | @JvmOverloads fun File.readList(charset: Charset = Charsets.UTF_8): List { 72 | return FileInputStream(this).readList(charset) 73 | } 74 | 75 | @Throws(IOException::class) 76 | @JvmOverloads fun OutputStream.writeString(string: String, charset: Charset = Charsets.UTF_8) { 77 | this.writer(charset).write(string) 78 | } 79 | 80 | 81 | @Throws(IOException::class) 82 | @JvmOverloads fun Writer.writeList(lines: Collection<*>?, 83 | lineSeparator: String = Const.LINE_SEPARATOR) { 84 | lines?.forEach { line -> 85 | if (line != null) { 86 | this.write(line.toString()) 87 | } 88 | this.write(lineSeparator) 89 | } 90 | } 91 | 92 | @Throws(IOException::class) 93 | @JvmOverloads fun OutputStream.writeList(lines: Collection<*>?, 94 | charset: Charset = Charsets.UTF_8, 95 | lineSeparator: String = Const.LINE_SEPARATOR) { 96 | lines?.forEach { line -> 97 | if (line != null) { 98 | this.write(line.toString().toByteArray(charset)) 99 | } 100 | this.write(lineSeparator.toByteArray(charset)) 101 | } 102 | } 103 | 104 | @Throws(IOException::class) 105 | @JvmOverloads fun File.writeList(lines: Collection<*>?, 106 | charset: Charset = Charsets.UTF_8, 107 | lineSeparator: String = Const.LINE_SEPARATOR) { 108 | return FileOutputStream(this).writeList(lines, charset, lineSeparator) 109 | } 110 | 111 | fun File.clean(): Boolean { 112 | val file = this 113 | if (!file.exists()) { 114 | return true 115 | } 116 | if (file.isFile) { 117 | return file.delete() 118 | } 119 | if (!file.isDirectory) { 120 | return false 121 | } 122 | for (f in file.listFiles()) { 123 | if (f.isFile) { 124 | f.delete() 125 | } else if (f.isDirectory) { 126 | f.clean() 127 | } 128 | } 129 | return file.delete() 130 | } 131 | 132 | 133 | 134 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Intent.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Activity 4 | import android.app.Service 5 | import android.content.ComponentName 6 | import android.content.Context 7 | import android.content.Intent 8 | import android.os.Bundle 9 | 10 | /** 11 | * User: mcxiaoke 12 | * Date: 16/1/27 13 | * Time: 11:26 14 | */ 15 | 16 | 17 | inline fun Context.newIntent(): Intent = 18 | Intent(this, T::class.java) 19 | 20 | inline fun Context.newIntent(flags: Int): Intent { 21 | val intent = newIntent() 22 | intent.flags = flags 23 | return intent 24 | } 25 | 26 | inline fun Context.newIntent(extras: Bundle): Intent = 27 | newIntent(0, extras) 28 | 29 | inline fun Context.newIntent(flags: Int, extras: Bundle): Intent { 30 | val intent = newIntent(flags) 31 | intent.putExtras(extras) 32 | return intent 33 | } 34 | 35 | inline fun Activity.startActivity(): Unit = 36 | this.startActivity(newIntent()) 37 | 38 | inline fun Activity.startActivity(flags: Int): Unit = 39 | this.startActivity(newIntent(flags)) 40 | 41 | inline fun Activity.startActivity(extras: Bundle): Unit = 42 | this.startActivity(newIntent(extras)) 43 | 44 | inline fun Activity.startActivity(flags: Int, extras: Bundle): Unit = 45 | this.startActivity(newIntent(flags, extras)) 46 | 47 | inline fun Activity.startActivityForResult(requestCode: Int): Unit = 48 | this.startActivityForResult(newIntent(), requestCode) 49 | 50 | inline fun Activity.startActivityForResult(requestCode: Int, 51 | flags: Int): Unit = 52 | this.startActivityForResult(newIntent(flags), requestCode) 53 | 54 | inline fun Activity.startActivityForResult( 55 | extras: Bundle, requestCode: Int): Unit = 56 | this.startActivityForResult(newIntent(extras), requestCode) 57 | 58 | inline fun Activity.startActivityForResult( 59 | extras: Bundle, requestCode: Int, flags: Int): Unit = 60 | this.startActivityForResult(newIntent(flags, extras), requestCode) 61 | 62 | inline fun Context.startService(): ComponentName = 63 | this.startService(newIntent()) 64 | 65 | inline fun Context.startService(flags: Int): ComponentName = 66 | this.startService(newIntent(flags)) 67 | 68 | inline fun Context.startService(extras: Bundle): ComponentName = 69 | this.startService(newIntent(extras)) 70 | 71 | inline fun Context.startService(extras: Bundle, 72 | flags: Int): ComponentName 73 | = this.startService(newIntent(flags, extras)) 74 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Math.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/30 6 | * Time: 11:29 7 | */ 8 | 9 | fun Double.sin(): Double = Math.sin(this) 10 | 11 | fun Double.cos(): Double = Math.cos(this) 12 | fun Double.tan(): Double = Math.tan(this) 13 | fun Double.asin(): Double = Math.asin(this) 14 | fun Double.acos(): Double = Math.acos(this) 15 | fun Double.atan(): Double = Math.atan(this) 16 | fun Double.toRadians(): Double = Math.toRadians(this) 17 | fun Double.toDegrees(): Double = Math.toDegrees(this) 18 | fun Double.exp(): Double = Math.exp(this) 19 | fun Double.log(): Double = Math.log(this) 20 | fun Double.log10(): Double = Math.log10(this) 21 | fun Double.sqrt(): Double = Math.sqrt(this) 22 | fun Double.cbrt(): Double = Math.cbrt(this) 23 | fun Double.IEEEremainder(divisor: Double): Double = Math.IEEEremainder(this, divisor) 24 | fun Double.ceil(): Double = Math.ceil(this) 25 | fun Double.floor(): Double = Math.floor(this) 26 | fun Double.rint(): Double = Math.rint(this) 27 | fun Double.atan2(x: Double): Double = Math.atan2(this, x) 28 | fun Double.pow(exp: Double): Double = Math.pow(this, exp) 29 | fun Double.round(): Long = Math.round(this) 30 | fun Double.abs(): Double = Math.abs(this) 31 | fun Double.ulp(): Double = Math.ulp(this) 32 | fun Double.signum(): Double = Math.signum(this) 33 | fun Double.sinh(): Double = Math.sinh(this) 34 | fun Double.cosh(): Double = Math.cosh(this) 35 | fun Double.tanh(): Double = Math.tanh(this) 36 | fun Double.expm1(): Double = Math.expm1(this) 37 | fun Double.log1p(): Double = Math.log1p(this) 38 | fun Double.copySign(sign: Double): Double = Math.copySign(this, sign) 39 | fun Double.exponent(): Int = Math.getExponent(this) 40 | fun Double.next(direction: Double): Double = Math.nextAfter(this, direction) 41 | fun Double.nextUp(): Double = Math.nextUp(this) 42 | fun Double.scalb(scaleFactor: Int): Double = Math.scalb(this, scaleFactor) 43 | fun Double.clamp(min: Double, max: Double): Double = Math.max(min, Math.min(this, max)) 44 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Network.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.content.Context 4 | import android.net.ConnectivityManager 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/27 9 | * Time: 11:28 10 | */ 11 | 12 | enum class NetworkType { 13 | WIFI, MOBILE, OTHER, NONE 14 | } 15 | 16 | fun Context.networkTypeName(): String { 17 | var result = "(No Network)" 18 | try { 19 | val cm = this.getConnectivityManager() 20 | val info = cm.activeNetworkInfo 21 | if (info == null || !info.isConnectedOrConnecting) { 22 | return result 23 | } 24 | result = info.typeName 25 | if (info.type == ConnectivityManager.TYPE_MOBILE) { 26 | result += info.subtypeName 27 | } 28 | } catch (ignored: Throwable) { 29 | } 30 | return result 31 | } 32 | 33 | fun Context.networkOperator(): String { 34 | val tm = this.getTelephonyManager() 35 | return tm.networkOperator 36 | } 37 | 38 | fun Context.networkType(): NetworkType { 39 | val cm = this.getConnectivityManager() 40 | val info = cm.activeNetworkInfo 41 | if (info == null || !info.isConnectedOrConnecting) { 42 | return NetworkType.NONE 43 | } 44 | val type = info.type 45 | if (ConnectivityManager.TYPE_WIFI == type) { 46 | return NetworkType.WIFI 47 | } else if (ConnectivityManager.TYPE_MOBILE == type) { 48 | return NetworkType.MOBILE 49 | } else { 50 | return NetworkType.OTHER 51 | } 52 | } 53 | 54 | fun Context.isWifi(): Boolean { 55 | return networkType() == NetworkType.WIFI 56 | } 57 | 58 | fun Context.isMobile(): Boolean { 59 | return networkType() == NetworkType.MOBILE 60 | } 61 | 62 | fun Context.isConnected(): Boolean { 63 | val cm = this.getConnectivityManager() 64 | val info = cm.activeNetworkInfo 65 | return info != null && info.isConnectedOrConnecting 66 | } 67 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Package.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.ActivityManager 4 | import android.content.ComponentName 5 | import android.content.Context 6 | import android.content.pm.PackageInfo 7 | import android.content.pm.PackageManager 8 | import android.content.pm.Signature 9 | import com.mcxiaoke.koi.HASH 10 | import java.io.ByteArrayInputStream 11 | import java.security.cert.CertificateFactory 12 | import java.security.cert.X509Certificate 13 | 14 | /** 15 | * User: mcxiaoke 16 | * Date: 16/1/27 17 | * Time: 11:33 18 | */ 19 | 20 | 21 | fun Context.isAppInstalled(packageName: String): Boolean { 22 | try { 23 | return this.packageManager.getPackageInfo(packageName, 0) != null 24 | } catch (e: PackageManager.NameNotFoundException) { 25 | return false 26 | } 27 | } 28 | 29 | fun Context.isAppEnabled(packageName: String): Boolean { 30 | return try { 31 | packageManager.getApplicationInfo(packageName, 0)?.enabled ?: false 32 | } catch (e: PackageManager.NameNotFoundException) { 33 | false 34 | } 35 | } 36 | 37 | fun Context.isMainProcess(): Boolean { 38 | val am: ActivityManager = this.getActivityManager() 39 | val processes = am.runningAppProcesses 40 | val mainProcessName = this.packageName 41 | val myPid = android.os.Process.myPid() 42 | return processes.any { p -> 43 | p.pid == myPid 44 | && mainProcessName == p.processName 45 | } 46 | } 47 | 48 | fun Context.isComponentDisabled(clazz: Class<*>): Boolean { 49 | val componentName = ComponentName(this, clazz) 50 | val pm = this.packageManager 51 | return pm.getComponentEnabledSetting(componentName) == 52 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED 53 | } 54 | 55 | fun Context.isComponentEnabled(clazz: Class<*>): Boolean { 56 | val componentName = ComponentName(this, clazz) 57 | val pm = this.packageManager 58 | return pm.getComponentEnabledSetting(componentName) != 59 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED 60 | } 61 | 62 | fun Context.enableComponent(clazz: Class<*>) { 63 | return setComponentState(clazz, true) 64 | } 65 | 66 | fun Context.disableComponent(clazz: Class<*>) { 67 | return setComponentState(clazz, false) 68 | } 69 | 70 | fun Context.setComponentState(clazz: Class<*>, enable: Boolean) { 71 | val componentName = ComponentName(this, clazz) 72 | val pm = this.packageManager 73 | val oldState = pm.getComponentEnabledSetting(componentName) 74 | val newState = if (enable) 75 | PackageManager.COMPONENT_ENABLED_STATE_ENABLED 76 | else 77 | PackageManager.COMPONENT_ENABLED_STATE_DISABLED 78 | if (newState != oldState) { 79 | val flags = PackageManager.DONT_KILL_APP 80 | pm.setComponentEnabledSetting(componentName, newState, flags) 81 | } 82 | } 83 | 84 | 85 | fun Context.getPackageSignature(): Signature? { 86 | val pm = this.packageManager 87 | var info: PackageInfo? = null 88 | try { 89 | info = pm.getPackageInfo(this.packageName, PackageManager.GET_SIGNATURES) 90 | } catch (ignored: Exception) { 91 | } 92 | return info?.signatures?.get(0) 93 | } 94 | 95 | fun Context.getSignature(): String { 96 | val signature = this.getPackageSignature() 97 | if (signature != null) { 98 | try { 99 | return HASH.sha1(signature.toByteArray()) 100 | } catch (e: Exception) { 101 | return "" 102 | } 103 | } 104 | return "" 105 | } 106 | 107 | fun Context.dumpSignature(): String { 108 | val signature = this.getPackageSignature() ?: return "" 109 | val builder = StringBuilder() 110 | try { 111 | val signatureBytes = signature.toByteArray() 112 | val certFactory = CertificateFactory.getInstance("X.509") 113 | val input = ByteArrayInputStream(signatureBytes) 114 | val cert = certFactory.generateCertificate(input) as X509Certificate 115 | val chars = signature.toCharsString() 116 | val hex = HASH.encodeHex(signatureBytes, false) 117 | val md5 = HASH.md5(signatureBytes) 118 | val sha1 = HASH.sha1(signatureBytes) 119 | builder.append("SignName:").append(cert.sigAlgName).append("\n") 120 | builder.append("Chars:").append(chars).append("\n") 121 | builder.append("Hex:").append(hex).append("\n") 122 | builder.append("MD5:").append(md5).append("\n") 123 | builder.append("SHA1:").append(sha1).append("\n") 124 | builder.append("SignNumber:").append(cert.serialNumber).append("\n") 125 | builder.append("SubjectDN:").append(cert.subjectDN.name).append("\n") 126 | builder.append("IssuerDN:").append(cert.issuerDN.name).append("\n") 127 | } catch (e: Exception) { 128 | builder.append("Error:" + e) 129 | } 130 | return builder.toString() 131 | } 132 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Parcelable.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.os.Parcel 4 | import android.os.Parcelable 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/30 9 | * Time: 11:15 10 | */ 11 | 12 | inline fun createParcel(crossinline createFromParcel: (Parcel) -> T?): Parcelable.Creator = 13 | object : Parcelable.Creator { 14 | override fun createFromParcel(source: Parcel): T? = createFromParcel(source) 15 | override fun newArray(size: Int): Array = arrayOfNulls(size) 16 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Primitives.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.content.res.Resources 4 | import com.mcxiaoke.koi.Const 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/22 9 | * Time: 13:42 10 | */ 11 | 12 | fun Long.readableByteCount(): String { 13 | val unit = 1024 14 | if (this < unit) return "${this}B" 15 | val exp = (Math.log(this.toDouble()) / Math.log(unit.toDouble())).toInt() 16 | val pre = "KMGTPE"[exp - 1] + "" 17 | return "%.1f %sB".format(this / Math.pow(unit.toDouble(), exp.toDouble()), pre) 18 | } 19 | 20 | fun ByteArray.hexString(): String { 21 | val hexChars = CharArray(this.size * 2) 22 | forEachIndexed { i, byte -> 23 | val v = byte.toInt() and 255 24 | hexChars[i * 2] = Const.HEX_DIGITS[v.ushr(4)] 25 | hexChars[i * 2 + 1] = Const.HEX_DIGITS[v and 15] 26 | } 27 | return String(hexChars) 28 | } 29 | 30 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/String.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import com.mcxiaoke.koi.Const 4 | import com.mcxiaoke.koi.Encoding 5 | import java.io.File 6 | import java.io.UnsupportedEncodingException 7 | import java.math.BigInteger 8 | import java.net.URLDecoder 9 | import java.util.* 10 | 11 | /** 12 | * User: mcxiaoke 13 | * Date: 16/1/22 14 | * Time: 13:35 15 | */ 16 | 17 | fun String.quote(): String { 18 | return "'$this'" 19 | } 20 | 21 | fun CharSequence.isBlank(): Boolean { 22 | val len: Int = this.length 23 | if (len == 0) { 24 | return true 25 | } 26 | forEach { c -> 27 | if (!Character.isWhitespace(c)) { 28 | return false 29 | } 30 | } 31 | return true 32 | } 33 | 34 | fun String.toHexBytes(): ByteArray { 35 | val len = this.length 36 | val data = ByteArray(len / 2) 37 | var i = 0 38 | while (i < len) { 39 | data[i / 2] = ((Character.digit(this[i], 16) shl 4) 40 | + Character.digit(this[i + 1], 16)).toByte() 41 | i += 2 42 | } 43 | return data 44 | } 45 | 46 | fun String.withoutQuery(): String { 47 | return this.split("\\?".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0] 48 | } 49 | 50 | fun String?.isNameSafe(): Boolean { 51 | // Note, we check whether it matches what's known to be safe, 52 | // rather than what's known to be unsafe. Non-ASCII, control 53 | // characters, etc. are all unsafe by default. 54 | if (this == null) { 55 | return false 56 | } 57 | return Const.SAFE_FILENAME_PATTERN.matcher(this).matches() 58 | } 59 | 60 | fun String.toSafeFileName(): String { 61 | val size = this.length 62 | val builder = StringBuilder(size * 2) 63 | forEachIndexed { i, c -> 64 | var valid = c in 'a'..'z' 65 | valid = valid || c in 'A'..'Z' 66 | valid = valid || c in '0'..'9' 67 | valid = valid || c == '_' || c == '-' || c == '.' 68 | 69 | if (valid) { 70 | builder.append(c) 71 | } else { 72 | // Encode the character using hex notation 73 | builder.append('x') 74 | builder.append(Integer.toHexString(i)) 75 | } 76 | } 77 | return builder.toString() 78 | } 79 | 80 | fun String.toQueries(): Map { 81 | val map: Map = mapOf() 82 | if (this.isEmpty()) { 83 | return map 84 | } 85 | try { 86 | val queries = HashMap() 87 | for (param in this.split("&".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) { 88 | val pair = param.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() 89 | val key = URLDecoder.decode(pair[0], Encoding.UTF_8) 90 | if (pair.size > 1) { 91 | val value = URLDecoder.decode(pair[1], Encoding.UTF_8) 92 | queries.put(key, value) 93 | } 94 | } 95 | return queries 96 | } catch (ex: UnsupportedEncodingException) { 97 | throw RuntimeException(ex) 98 | } 99 | 100 | } 101 | 102 | @JvmOverloads fun String.toStringList(delimiters: String = "?", 103 | trimTokens: Boolean = true, 104 | ignoreEmptyTokens: Boolean = true): List { 105 | val st = StringTokenizer(this, delimiters) 106 | val tokens = ArrayList() 107 | while (st.hasMoreTokens()) { 108 | var token = st.nextToken() 109 | if (trimTokens) { 110 | token = token.trim { it <= ' ' } 111 | } 112 | if (!ignoreEmptyTokens || token.isNotEmpty()) { 113 | tokens.add(token) 114 | } 115 | } 116 | return tokens 117 | } 118 | 119 | @JvmOverloads fun String.toStringArray(delimiters: String = "?", 120 | trimTokens: Boolean = true, 121 | ignoreEmptyTokens: Boolean = true): Array { 122 | return toStringList(delimiters, trimTokens, ignoreEmptyTokens).toTypedArray() 123 | } 124 | 125 | 126 | fun String.trimLeadingCharacter(leadingCharacter: Char): String { 127 | if (this.isEmpty()) { 128 | return this 129 | } 130 | val sb = StringBuilder(this) 131 | while (sb.isNotEmpty() && sb[0] == leadingCharacter) { 132 | sb.deleteCharAt(0) 133 | } 134 | return sb.toString() 135 | } 136 | 137 | fun String.trimTrailingCharacter(trailingCharacter: Char): String { 138 | if (this.isEmpty()) { 139 | return this 140 | } 141 | val sb = StringBuilder(this) 142 | while (sb.isNotEmpty() && sb[sb.length - 1] == trailingCharacter) { 143 | sb.deleteCharAt(sb.length - 1) 144 | } 145 | return sb.toString() 146 | } 147 | 148 | fun String.trimAllWhitespace(): String { 149 | if (this.isEmpty()) { 150 | return this 151 | } 152 | val sb = StringBuilder(this) 153 | var index = 0 154 | while (sb.length > index) { 155 | if (Character.isWhitespace(sb[index])) { 156 | sb.deleteCharAt(index) 157 | } else { 158 | index++ 159 | } 160 | } 161 | return sb.toString() 162 | } 163 | 164 | fun CharSequence.containsWhitespace(): Boolean { 165 | if (this.isEmpty()) { 166 | return false 167 | } 168 | forEach { c -> 169 | if (Character.isWhitespace(c)) { 170 | return true 171 | } 172 | } 173 | return false 174 | } 175 | 176 | 177 | fun String.fileNameWithoutExtension(): String { 178 | if (isEmpty()) { 179 | return this 180 | } 181 | 182 | var filePath = this 183 | val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) 184 | val filePosi = filePath.lastIndexOf(File.separator) 185 | if (filePosi == -1) { 186 | return if (extenPosi == -1) filePath else filePath.substring(0, extenPosi) 187 | } 188 | if (extenPosi == -1) { 189 | return filePath.substring(filePosi + 1) 190 | } 191 | return if (filePosi < extenPosi) filePath.substring(filePosi + 1, extenPosi) 192 | else filePath.substring(filePosi + 1) 193 | } 194 | 195 | fun String.fileName(): String { 196 | if (isEmpty()) { 197 | return this 198 | } 199 | 200 | var filePath = this 201 | val filePosi = filePath.lastIndexOf(File.separator) 202 | return if (filePosi == -1) filePath else filePath.substring(filePosi + 1) 203 | } 204 | 205 | fun String.fileExtension(): String { 206 | if (isEmpty()) { 207 | return this 208 | } 209 | var filePath = this 210 | val extenPosi = filePath.lastIndexOf(Const.FILE_EXTENSION_SEPARATOR) 211 | val filePosi = filePath.lastIndexOf(File.separator) 212 | if (extenPosi == -1) { 213 | return "" 214 | } 215 | return if (filePosi >= extenPosi) "" else filePath.substring(extenPosi + 1) 216 | } 217 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/SystemService.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/26 6 | * Time: 17:35 7 | */ 8 | 9 | import android.accounts.AccountManager 10 | import android.annotation.TargetApi 11 | import android.app.* 12 | import android.app.admin.DevicePolicyManager 13 | import android.app.job.JobScheduler 14 | import android.appwidget.AppWidgetManager 15 | import android.bluetooth.BluetoothAdapter 16 | import android.content.ClipboardManager 17 | import android.content.Context 18 | import android.content.RestrictionsManager 19 | import android.content.pm.LauncherApps 20 | import android.hardware.ConsumerIrManager 21 | import android.hardware.SensorManager 22 | import android.hardware.camera2.CameraManager 23 | import android.hardware.display.DisplayManager 24 | import android.hardware.input.InputManager 25 | import android.hardware.usb.UsbManager 26 | import android.location.LocationManager 27 | import android.media.AudioManager 28 | import android.media.MediaRouter 29 | import android.media.projection.MediaProjectionManager 30 | import android.media.session.MediaSessionManager 31 | import android.media.tv.TvInputManager 32 | import android.net.ConnectivityManager 33 | import android.net.nsd.NsdManager 34 | import android.net.wifi.WifiManager 35 | import android.net.wifi.p2p.WifiP2pManager 36 | import android.nfc.NfcManager 37 | import android.os.* 38 | import android.os.storage.StorageManager 39 | import android.print.PrintManager 40 | import android.service.wallpaper.WallpaperService 41 | import android.telephony.TelephonyManager 42 | import android.view.LayoutInflater 43 | import android.view.WindowManager 44 | import android.view.accessibility.AccessibilityManager 45 | import android.view.accessibility.CaptioningManager 46 | import android.view.inputmethod.InputMethodManager 47 | import android.view.textservice.TextServicesManager 48 | 49 | 50 | fun Context.getAccessibilityManager(): AccessibilityManager = 51 | getSystemServiceAs(Context.ACCESSIBILITY_SERVICE) 52 | 53 | fun Context.getAccountManager(): AccountManager = 54 | getSystemServiceAs(Context.ACCOUNT_SERVICE) 55 | 56 | fun Context.getActivityManager(): ActivityManager = 57 | getSystemServiceAs(Context.ACTIVITY_SERVICE) 58 | 59 | fun Context.getAlarmManager(): AlarmManager = 60 | getSystemServiceAs(Context.ALARM_SERVICE) 61 | 62 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 63 | fun Context.getAppWidgetManager(): AppWidgetManager = 64 | getSystemServiceAs(Context.APPWIDGET_SERVICE) 65 | 66 | @TargetApi(Build.VERSION_CODES.KITKAT) 67 | fun Context.getAppOpsManager(): AppOpsManager = 68 | getSystemServiceAs(Context.APP_OPS_SERVICE) 69 | 70 | fun Context.getAudioManager(): AudioManager = 71 | getSystemServiceAs(Context.AUDIO_SERVICE) 72 | 73 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 74 | fun Context.getBatteryManager(): BatteryManager = 75 | getSystemServiceAs(Context.BATTERY_SERVICE) 76 | 77 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 78 | fun Context.getBluetoothAdapter(): BluetoothAdapter = 79 | getSystemServiceAs(Context.BLUETOOTH_SERVICE) 80 | 81 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 82 | fun Context.getCameraManager(): CameraManager = 83 | getSystemServiceAs(Context.CAMERA_SERVICE) 84 | 85 | @TargetApi(Build.VERSION_CODES.KITKAT) 86 | fun Context.getCaptioningManager(): CaptioningManager = 87 | getSystemServiceAs(Context.CAPTIONING_SERVICE) 88 | 89 | fun Context.getClipboardManager(): ClipboardManager = 90 | getSystemServiceAs(Context.CLIPBOARD_SERVICE) 91 | 92 | fun Context.getConnectivityManager(): ConnectivityManager = 93 | getSystemServiceAs(Context.CONNECTIVITY_SERVICE) 94 | 95 | @TargetApi(Build.VERSION_CODES.KITKAT) 96 | fun Context.getConsumerIrManager(): ConsumerIrManager = 97 | getSystemServiceAs(Context.CONSUMER_IR_SERVICE) 98 | 99 | fun Context.getDevicePolicyManager(): DevicePolicyManager = 100 | getSystemServiceAs(Context.DEVICE_POLICY_SERVICE) 101 | 102 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 103 | fun Context.getDisplayManager(): DisplayManager = 104 | getSystemServiceAs(Context.DISPLAY_SERVICE) 105 | 106 | fun Context.getDownloadManager(): DownloadManager = 107 | getSystemServiceAs(Context.DOWNLOAD_SERVICE) 108 | 109 | fun Context.getDropBoxManager(): DropBoxManager = 110 | getSystemServiceAs(Context.DROPBOX_SERVICE) 111 | 112 | fun Context.getInputMethodManager(): InputMethodManager = 113 | getSystemServiceAs(Context.INPUT_METHOD_SERVICE) 114 | 115 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 116 | fun Context.getInputManager(): InputManager = 117 | getSystemServiceAs(Context.INPUT_SERVICE) 118 | 119 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 120 | fun Context.getJobScheduler(): JobScheduler = 121 | getSystemServiceAs(Context.JOB_SCHEDULER_SERVICE) 122 | 123 | fun Context.getKeyguardManager(): KeyguardManager = 124 | getSystemServiceAs(Context.KEYGUARD_SERVICE) 125 | 126 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 127 | fun Context.getLauncherApps(): LauncherApps = 128 | getSystemServiceAs(Context.LAUNCHER_APPS_SERVICE) 129 | 130 | fun Context.getLayoutService(): LayoutInflater = 131 | getSystemServiceAs(Context.LAYOUT_INFLATER_SERVICE) 132 | 133 | fun Context.getLocationManager(): LocationManager = 134 | getSystemServiceAs(Context.LOCATION_SERVICE) 135 | 136 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 137 | fun Context.getMediaProjectionManager(): MediaProjectionManager = 138 | getSystemServiceAs(Context.MEDIA_PROJECTION_SERVICE) 139 | 140 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 141 | fun Context.getMediaRouter(): MediaRouter = 142 | getSystemServiceAs(Context.MEDIA_ROUTER_SERVICE) 143 | 144 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 145 | fun Context.getMediaSessionManager(): MediaSessionManager = 146 | getSystemServiceAs(Context.MEDIA_SESSION_SERVICE) 147 | 148 | fun Context.getNfcManager(): NfcManager = 149 | getSystemServiceAs(Context.NFC_SERVICE) 150 | 151 | fun Context.getNotificationManager(): NotificationManager = 152 | getSystemServiceAs(Context.NOTIFICATION_SERVICE) 153 | 154 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 155 | fun Context.getNsdManager(): NsdManager = 156 | getSystemServiceAs(Context.NSD_SERVICE) 157 | 158 | fun Context.getPowerManager(): PowerManager = 159 | getSystemServiceAs(Context.POWER_SERVICE) 160 | 161 | @TargetApi(Build.VERSION_CODES.KITKAT) 162 | fun Context.getPrintManager(): PrintManager = 163 | getSystemServiceAs(Context.PRINT_SERVICE) 164 | 165 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 166 | fun Context.getRestrictionsManager(): RestrictionsManager = 167 | getSystemServiceAs(Context.RESTRICTIONS_SERVICE) 168 | 169 | fun Context.getSearchManager(): SearchManager = 170 | getSystemServiceAs(Context.SEARCH_SERVICE) 171 | 172 | fun Context.getSensorManager(): SensorManager = 173 | getSystemServiceAs(Context.SENSOR_SERVICE) 174 | 175 | fun Context.getStorageManager(): StorageManager = 176 | getSystemServiceAs(Context.STORAGE_SERVICE) 177 | 178 | fun Context.getTelephonyManager(): TelephonyManager = 179 | getSystemServiceAs(Context.TELEPHONY_SERVICE) 180 | 181 | fun Context.getTextServicesManager(): TextServicesManager = 182 | getSystemServiceAs(Context.TEXT_SERVICES_MANAGER_SERVICE) 183 | 184 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 185 | fun Context.getTvInputManager(): TvInputManager = 186 | getSystemServiceAs(Context.TV_INPUT_SERVICE) 187 | 188 | fun Context.getUiModeManager(): UiModeManager = 189 | getSystemServiceAs(Context.UI_MODE_SERVICE) 190 | 191 | fun Context.getUsbManager(): UsbManager = 192 | getSystemServiceAs(Context.USB_SERVICE) 193 | 194 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) 195 | fun Context.getUserManager(): UserManager = 196 | getSystemServiceAs(Context.USER_SERVICE) 197 | 198 | fun Context.getVibrator(): Vibrator = 199 | getSystemServiceAs(Context.VIBRATOR_SERVICE) 200 | 201 | fun Context.getWallpaperService(): WallpaperService = 202 | getSystemServiceAs(Context.WALLPAPER_SERVICE) 203 | 204 | fun Context.getWifiP2pManager(): WifiP2pManager = 205 | getSystemServiceAs(Context.WIFI_P2P_SERVICE) 206 | 207 | fun Context.getWifiManager(): WifiManager = 208 | getSystemServiceAs(Context.WIFI_SERVICE) 209 | 210 | fun Context.getWindowService(): WindowManager = 211 | getSystemServiceAs(Context.WINDOW_SERVICE) 212 | 213 | @Suppress("UNCHECKED_CAST") 214 | fun Context.getSystemServiceAs(serviceName: String): T = 215 | this.getSystemService(serviceName) as T 216 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/Toast.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Fragment 4 | import android.content.Context 5 | import android.view.View 6 | import android.widget.Toast 7 | import android.support.v4.app.Fragment as SupportFragment 8 | 9 | /** 10 | * User: mcxiaoke 11 | * Date: 16/1/27 12 | * Time: 11:28 13 | */ 14 | 15 | 16 | fun Context.toast(resId: Int) { 17 | Toast.makeText(this, resId, Toast.LENGTH_SHORT).show() 18 | } 19 | 20 | fun Context.toast(text: CharSequence) { 21 | Toast.makeText(this, text, Toast.LENGTH_SHORT).show() 22 | } 23 | 24 | fun Context.longToast(resId: Int) { 25 | Toast.makeText(this, resId, Toast.LENGTH_LONG).show() 26 | } 27 | 28 | fun Context.longToast(text: CharSequence) { 29 | Toast.makeText(this, text, Toast.LENGTH_LONG).show() 30 | } 31 | 32 | fun View.toast(resId: Int) = context.toast(resId) 33 | 34 | fun View.toast(text: CharSequence) = context.toast(text) 35 | 36 | fun View.longToast(resId: Int) = context.longToast(resId) 37 | 38 | fun View.longToast(text: CharSequence) = context.longToast(text) 39 | 40 | fun Fragment.toast(resId: Int) = activity.toast(resId) 41 | 42 | fun Fragment.toast(text: CharSequence) = activity.toast(text) 43 | 44 | fun Fragment.longToast(resId: Int) = activity.longToast(resId) 45 | 46 | fun Fragment.longToast(text: CharSequence) = activity.longToast(text) 47 | 48 | fun SupportFragment.toast(resId: Int) = activity.toast(resId) 49 | 50 | fun SupportFragment.toast(text: CharSequence) = activity.toast(text) 51 | 52 | fun SupportFragment.longToast(resId: Int) = activity.longToast(resId) 53 | 54 | fun SupportFragment.longToast(text: CharSequence) = activity.longToast(text) -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/ext/View.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ext 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import android.content.Context 6 | import android.content.res.Resources 7 | import android.text.Editable 8 | import android.text.TextWatcher 9 | import android.util.DisplayMetrics 10 | import android.view.* 11 | import android.view.inputmethod.InputMethodManager 12 | import android.widget.* 13 | import android.support.v4.app.Fragment as SupportFragment 14 | 15 | /** 16 | * User: mcxiaoke 17 | * Date: 16/1/26 18 | * Time: 17:38 19 | */ 20 | 21 | 22 | val View.dm: DisplayMetrics 23 | get() = resources.displayMetrics 24 | 25 | 26 | fun Float.pxToDp(): Int { 27 | val metrics = Resources.getSystem().displayMetrics 28 | val dp = this / (metrics.densityDpi / 160f) 29 | return Math.round(dp) 30 | } 31 | 32 | fun Float.dpToPx(): Int { 33 | val metrics = Resources.getSystem().displayMetrics 34 | val px = this * (metrics.densityDpi / 160f) 35 | return Math.round(px) 36 | } 37 | 38 | fun Int.pxToDp(): Int { 39 | val metrics = Resources.getSystem().displayMetrics 40 | val dp = this / (metrics.densityDpi / 160f) 41 | return Math.round(dp) 42 | } 43 | 44 | fun Int.dpToPx(): Int { 45 | val metrics = Resources.getSystem().displayMetrics 46 | val px = this * (metrics.densityDpi / 160f) 47 | return Math.round(px) 48 | } 49 | 50 | fun View.dpToPx(dp: Int): Int { 51 | return (dp * this.dm.density + 0.5).toInt() 52 | } 53 | 54 | fun View.pxToDp(px: Int): Int { 55 | return (px / this.dm.density + 0.5).toInt() 56 | } 57 | 58 | fun View.hideSoftKeyboard() { 59 | context.getInputMethodManager().hideSoftInputFromWindow(this.windowToken, 0) 60 | } 61 | 62 | fun EditText.showSoftKeyboard() { 63 | if (this.requestFocus()) { 64 | context.getInputMethodManager().showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) 65 | } 66 | } 67 | 68 | fun EditText.toggleSoftKeyboard() { 69 | if (this.requestFocus()) { 70 | context.getInputMethodManager().toggleSoftInput(0, 0) 71 | } 72 | } 73 | 74 | fun View.onClick(f: (View) -> Unit) { 75 | this.setOnClickListener(f) 76 | } 77 | 78 | fun View.onLongClick(f: (View) -> Boolean) { 79 | this.setOnLongClickListener(f) 80 | } 81 | 82 | fun View.onTouchEvent(f: (View, MotionEvent) -> Boolean) { 83 | this.setOnTouchListener(f) 84 | } 85 | 86 | fun View.onKeyEvent(f: (View, Int, KeyEvent) -> Boolean) { 87 | this.setOnKeyListener(f) 88 | } 89 | 90 | fun View.onFocusChange(f: (View, Boolean) -> Unit) { 91 | this.setOnFocusChangeListener(f) 92 | } 93 | 94 | fun CompoundButton.onCheckedChanged(f: (CompoundButton, Boolean) -> Unit) { 95 | this.setOnCheckedChangeListener(f) 96 | } 97 | 98 | fun AdapterView<*>.onItemClick(f: (AdapterView<*>, View, Int, Long) -> Unit) { 99 | this.setOnItemClickListener(f) 100 | } 101 | 102 | inline fun T.onScrollChanged( 103 | crossinline stateChanged: (View, Int) -> Unit) { 104 | val listener = object : AbsListView.OnScrollListener { 105 | override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { 106 | stateChanged(view, scrollState) 107 | } 108 | 109 | override fun onScroll(view: AbsListView, firstVisibleItem: Int, 110 | visibleItemCount: Int, totalItemCount: Int) { 111 | } 112 | } 113 | this.setOnScrollListener(listener) 114 | } 115 | 116 | inline fun EditText.onTextChange(crossinline f: (CharSequence, Int, Int, Int) -> Unit) { 117 | val listener = object : KoiTextWatcher() { 118 | override fun onTextChanged(s: CharSequence, start: Int, 119 | before: Int, count: Int) { 120 | f(s, start, before, count) 121 | } 122 | } 123 | this.addTextChangedListener(listener) 124 | } 125 | 126 | fun SeekBar.onProgressChanged(f: (SeekBar, Int, Boolean) -> Unit) { 127 | val listener = object : KoiSeekBarChangeListener() { 128 | override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { 129 | super.onProgressChanged(seekBar, progress, fromUser) 130 | f(seekBar, progress, fromUser) 131 | } 132 | } 133 | this.setOnSeekBarChangeListener(listener) 134 | } 135 | 136 | abstract class KoiTextWatcher : TextWatcher { 137 | override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { 138 | } 139 | 140 | override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { 141 | } 142 | 143 | override fun afterTextChanged(s: Editable) { 144 | } 145 | } 146 | 147 | abstract class KoiSeekBarChangeListener : SeekBar.OnSeekBarChangeListener { 148 | override fun onStopTrackingTouch(seekBar: SeekBar) { 149 | } 150 | 151 | override fun onStartTrackingTouch(seekBar: SeekBar) { 152 | } 153 | 154 | override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { 155 | } 156 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/log/Log.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.log 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/26 6 | * Time: 17:29 7 | */ 8 | 9 | import android.content.Context 10 | import android.util.Log 11 | import com.mcxiaoke.koi.KoiConfig 12 | import com.mcxiaoke.koi.threadName 13 | 14 | fun Throwable.stackTraceString(): String = Log.getStackTraceString(this) 15 | 16 | private fun logMessageWithThreadName(message: String): String 17 | = "$message [thread:${threadName()}]" 18 | 19 | fun Context.logv(message: String) { 20 | logv(javaClass.simpleName, message) 21 | } 22 | 23 | fun Context.logd(message: String) { 24 | logd(javaClass.simpleName, message) 25 | } 26 | 27 | fun Context.logi(message: String) { 28 | logi(javaClass.simpleName, message) 29 | } 30 | 31 | fun Context.logw(message: String) { 32 | logw(javaClass.simpleName, message) 33 | } 34 | 35 | fun Context.loge(message: String) { 36 | loge(javaClass.simpleName, message) 37 | } 38 | 39 | fun Context.logf(message: String) { 40 | logf(javaClass.simpleName, message) 41 | } 42 | 43 | fun logv(tag: String, message: String, exception: Throwable? = null) { 44 | if (KoiConfig.logLevel <= Log.VERBOSE) { 45 | Log.v(tag, logMessageWithThreadName(message), exception) 46 | } 47 | } 48 | 49 | fun logd(tag: String, message: String, exception: Throwable? = null) { 50 | if (KoiConfig.logLevel <= Log.DEBUG) { 51 | Log.d(tag, logMessageWithThreadName(message), exception) 52 | } 53 | } 54 | 55 | fun logi(tag: String, message: String, exception: Throwable? = null) { 56 | if (KoiConfig.logLevel <= Log.INFO) { 57 | Log.i(tag, logMessageWithThreadName(message), exception) 58 | } 59 | } 60 | 61 | fun logw(tag: String, message: String, exception: Throwable? = null) { 62 | if (KoiConfig.logLevel <= Log.WARN) { 63 | Log.w(tag, logMessageWithThreadName(message), exception) 64 | } 65 | } 66 | 67 | fun loge(tag: String, message: String, exception: Throwable? = null) { 68 | if (KoiConfig.logLevel <= Log.ERROR) { 69 | Log.e(tag, logMessageWithThreadName(message), exception) 70 | } 71 | } 72 | 73 | fun logf(tag: String, message: String, exception: Throwable? = null) { 74 | if (KoiConfig.logLevel <= Log.ERROR) { 75 | Log.wtf(tag, logMessageWithThreadName(message), exception) 76 | } 77 | } 78 | 79 | fun logw(tag: String, exception: Throwable?) { 80 | if (KoiConfig.logLevel <= Log.WARN) { 81 | Log.w(tag, logMessageWithThreadName("warn"), exception) 82 | } 83 | } 84 | 85 | fun logf(tag: String, exception: Throwable?) { 86 | if (KoiConfig.logLevel <= Log.ERROR) { 87 | Log.wtf(tag, logMessageWithThreadName("wtf"), exception) 88 | } 89 | } 90 | 91 | inline fun Context.logv(lazyMessage: () -> Any?) { 92 | logv(javaClass.simpleName, lazyMessage) 93 | } 94 | 95 | inline fun Context.logd(lazyMessage: () -> Any?) { 96 | logd(javaClass.simpleName, lazyMessage) 97 | } 98 | 99 | inline fun Context.logi(lazyMessage: () -> Any?) { 100 | logi(javaClass.simpleName, lazyMessage) 101 | } 102 | 103 | inline fun Context.logw(lazyMessage: () -> Any?) { 104 | logw(javaClass.simpleName, lazyMessage) 105 | } 106 | 107 | inline fun Context.loge(lazyMessage: () -> Any?) { 108 | loge(javaClass.simpleName, lazyMessage) 109 | } 110 | 111 | inline fun Context.logf(lazyMessage: () -> Any?) { 112 | logf(javaClass.simpleName, lazyMessage) 113 | } 114 | 115 | inline fun logv(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 116 | if (KoiConfig.logLevel <= Log.VERBOSE) { 117 | Log.v(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 118 | } 119 | } 120 | 121 | inline fun logd(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 122 | if (KoiConfig.logLevel <= Log.DEBUG) { 123 | Log.d(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 124 | } 125 | } 126 | 127 | inline fun logi(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 128 | if (KoiConfig.logLevel <= Log.INFO) { 129 | Log.i(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 130 | } 131 | } 132 | 133 | inline fun logw(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 134 | if (KoiConfig.logLevel <= Log.WARN) { 135 | Log.w(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 136 | } 137 | } 138 | 139 | inline fun loge(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 140 | if (KoiConfig.logLevel <= Log.ERROR) { 141 | Log.e(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 142 | } 143 | } 144 | 145 | inline fun logf(tag: String, lazyMessage: () -> Any?, exception: Throwable? = null) { 146 | if (KoiConfig.logLevel <= Log.ERROR) { 147 | Log.wtf(tag, (lazyMessage()?.toString() ?: "null") + " [T:${threadName()}]", exception) 148 | } 149 | } -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/utils/Platform.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.utils 2 | 3 | import android.os.Build 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/26 8 | * Time: 17:45 9 | */ 10 | 11 | fun beforeOreo(): Boolean = isOlderVersionThen(26) 12 | fun oreoOrNewer(): Boolean = isOnVersionOrNewer(26) 13 | fun beforeNougat(): Boolean = isOlderVersionThen(24) 14 | fun nougatOrNewer(): Boolean = isOnVersionOrNewer(24) 15 | fun beforeMarshmallow(): Boolean = isOlderVersionThen(23) 16 | fun marshmallowOrNewer(): Boolean = isOnVersionOrNewer(23) 17 | fun beforeLollipop(): Boolean = isOlderVersionThen(21) 18 | fun lollipopOrNewer(): Boolean = isOnVersionOrNewer(21) 19 | fun beforeKitkat(): Boolean = isOlderVersionThen(19) 20 | fun kitkatOrNewer(): Boolean = isOnVersionOrNewer(19) 21 | fun beforeIcs(): Boolean = isOlderVersionThen(14) 22 | fun icsOrNewer(): Boolean = isOnVersionOrNewer(14) 23 | fun beforeVersion(version: Int): Boolean = isOlderVersionThen(version) 24 | fun versionOrNewer(version: Int): Boolean = isOnVersionOrNewer(version) 25 | fun currentVersion(): Int = Build.VERSION.SDK_INT 26 | 27 | private fun isOlderVersionThen(version: Int) = Build.VERSION.SDK_INT < version 28 | 29 | private fun isOnVersionOrNewer(version: Int) = Build.VERSION.SDK_INT >= version 30 | -------------------------------------------------------------------------------- /core/src/main/kotlin/com/mcxiaoke/koi/utils/System.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.utils 2 | 3 | import android.content.Intent 4 | import android.os.BatteryManager 5 | import android.os.Environment 6 | import android.os.StatFs 7 | import com.mcxiaoke.koi.Const 8 | 9 | /** 10 | * User: mcxiaoke 11 | * Date: 16/1/27 12 | * Time: 11:06 13 | */ 14 | val isLargeHeap: Boolean 15 | get() = Runtime.getRuntime().maxMemory() > Const.HEAP_SIZE_LARGE 16 | 17 | 18 | fun noSdcard(): Boolean { 19 | return Environment.MEDIA_MOUNTED != Environment.getExternalStorageState() 20 | } 21 | 22 | /** 23 | * check if free size of SDCARD and CACHE dir is OK 24 | 25 | * @param needSize how much space should release at least 26 | * * 27 | * @return true if has enough space 28 | */ 29 | fun noFreeSpace(needSize: Long): Boolean { 30 | val freeSpace = freeSpace() 31 | return freeSpace < needSize * 3 32 | } 33 | 34 | fun freeSpace(): Long { 35 | val stat = StatFs(Environment.getExternalStorageDirectory().path) 36 | val blockSize = stat.blockSize.toLong() 37 | val availableBlocks = stat.availableBlocks.toLong() 38 | return availableBlocks * blockSize 39 | } 40 | 41 | fun getBatteryLevel(batteryIntent: Intent): Float { 42 | val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) 43 | val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) 44 | return level / scale.toFloat() 45 | } 46 | 47 | fun getBatteryInfo(batteryIntent: Intent): String { 48 | val status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1) 49 | val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING 50 | || status == BatteryManager.BATTERY_STATUS_FULL 51 | val chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1) 52 | val usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB 53 | val acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC 54 | 55 | val level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) 56 | val scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1) 57 | 58 | val batteryPct = level / scale.toFloat() 59 | return "Battery Info: isCharging=$isCharging usbCharge=$usbCharge acCharge=$acCharge batteryPct=$batteryPct" 60 | } 61 | -------------------------------------------------------------------------------- /deploy-local.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | echo "build and uploadArchives..." 3 | # upload archives to local 4 | ./gradlew clean uploadArchives -PRELEASE_REPOSITORY_URL=file:///tmp/ -PSNAPSHOT_REPOSITORY_URL=file:///tmp/ 5 | if [ $? -eq 0 ] 6 | then 7 | echo "deploy successful!" 8 | exit 0 9 | else 10 | echo "deploy failed!" 11 | exit 1 12 | fi 13 | -------------------------------------------------------------------------------- /deploy-remote.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | echo "build and uploadArchives..." 3 | ./gradlew clean uploadArchives --stacktrace 4 | if [ $? -eq 0 ] 5 | then 6 | echo "deploy successful!" 7 | exit 0 8 | else 9 | echo "deploy failed!" 10 | exit 1 11 | fi 12 | -------------------------------------------------------------------------------- /docs/kotlin-tutorial-basic01.md: -------------------------------------------------------------------------------- 1 | # Kotlin教程:基础篇(一) 2 | 3 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=0.5.5 2 | VERSION_CODE=505 3 | 4 | GROUP=com.mcxiaoke.koi 5 | 6 | POM_DESCRIPTION=Koi - Kotlin Library for Android Development 7 | POM_URL=https://github.com/mcxiaoke/kotlin-koi 8 | POM_SCM_URL=https://github.com/mcxiaoke/kotlin-koi.git 9 | POM_SCM_CONNECTION=scm:git:git@github.com:mcxiaoke/kotlin-koi.git 10 | POM_SCM_DEV_CONNECTION=scm:git:git@github.com:mcxiaoke/kotlin-koi.git 11 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 12 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 13 | POM_LICENCE_DIST=repo 14 | POM_DEVELOPER_ID=mcxiaoke 15 | POM_DEVELOPER_NAME=Xiaoke Zhang 16 | POM_DEVELOPER_EMAIL=mail@mcxiaoke.com 17 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcxiaoke/kotlin-koi/58e548a531e1f66ce4bd8535058cf8d4173c5709/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Feb 07 14:56:55 CST 2017 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-3.5-bin.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 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 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 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /network/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: '../base.gradle' 2 | //apply from: 'https://coding.net/u/mcxiaoke/p/gradle-mvn-push/git/raw/master/gradle-mvn-push.gradle' 3 | 4 | -------------------------------------------------------------------------------- /network/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Koi Library Network Module 2 | POM_ARTIFACT_ID=network 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /network/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /network/src/main/kotlin/com/mcxiaoke/koi/network/NetworkConfig.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.network 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/31 6 | * Time: 16:51 7 | */ 8 | -------------------------------------------------------------------------------- /samples/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | 3 | repositories { 4 | mavenCentral() 5 | jcenter() 6 | } 7 | 8 | dependencies { 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 10 | classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlinVersion" 11 | } 12 | } 13 | 14 | apply plugin: 'com.android.application' 15 | apply plugin: 'kotlin-android' 16 | apply plugin: 'kotlin-android-extensions' 17 | 18 | dependencies { 19 | // kapt 'com.jakewharton:butterknife:7.0.1' 20 | 21 | compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion" 22 | compile 'org.jetbrains.anko:anko-sdk15:0.8.2' // sdk19, sdk21, sdk23 are also available 23 | compile 'org.jetbrains.anko:anko-support-v4:0.8.2' // In case you need support-v4 bindings 24 | compile 'org.jetbrains.anko:anko-appcompat-v7:0.8.2' // For appcompat-v7 bindings 25 | 26 | compile "com.android.support:support-v4:$supportVersion" 27 | compile "com.android.support:recyclerview-v7:$supportVersion" 28 | compile "com.android.support:appcompat-v7:$supportVersion" 29 | compile "com.android.support:design:$supportVersion" 30 | 31 | compile 'com.google.code.gson:gson:2.5' 32 | // compile 'com.jakewharton:butterknife:7.0.1' 33 | compile 'com.squareup.okhttp:okhttp:2.7.4' 34 | 35 | compile 'com.mcxiaoke.next:task:1.3.0' 36 | compile 'com.mcxiaoke.next:core:1.3.0' 37 | compile 'com.mcxiaoke.next:http:1.3.0' 38 | compile 'com.mcxiaoke.next:ui:1.3.0' 39 | compile 'com.mcxiaoke.next:recycler:1.3.0' 40 | compile 'com.mcxiaoke.xbus:bus:1.0.2' 41 | 42 | compile project(':core') 43 | compile project(':async') 44 | compile project(':network') 45 | compile project(':ui') 46 | 47 | compile fileTree(dir: 'libs', include: '*.jar') 48 | } 49 | 50 | //kapt { 51 | // generateStubs = true 52 | //} 53 | 54 | android { 55 | compileSdkVersion rootProject.ext.compileSdkVersion 56 | buildToolsVersion rootProject.ext.buildToolsVersion 57 | 58 | defaultConfig { 59 | versionName project.VERSION_NAME 60 | versionCode Integer.parseInt(project.VERSION_CODE) 61 | minSdkVersion rootProject.ext.minSdkVersion 62 | targetSdkVersion rootProject.ext.targetSdkVersion 63 | } 64 | 65 | sourceSets { 66 | main.java.srcDirs += 'src/main/kotlin' 67 | } 68 | lintOptions { 69 | abortOnError false 70 | htmlReport true 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /samples/gradle.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcxiaoke/kotlin-koi/58e548a531e1f66ce4bd8535058cf8d4173c5709/samples/gradle.properties -------------------------------------------------------------------------------- /samples/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 14 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaApplication.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.app.Application; 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/29 8 | * Time: 21:45 9 | */ 10 | public class JavaApplication extends Application { 11 | 12 | @Override 13 | public void onCreate() { 14 | super.onCreate(); 15 | } 16 | 17 | public void test() { 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaFragment.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.annotation.TargetApi; 4 | import android.app.Fragment; 5 | import android.os.Build.VERSION_CODES; 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/29 10 | * Time: 21:42 11 | */ 12 | @TargetApi(VERSION_CODES.HONEYCOMB) 13 | public class JavaFragment extends Fragment { 14 | 15 | public JavaFragment() { 16 | super(); 17 | } 18 | 19 | public void test() { 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaFragmentV4.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.support.v4.app.Fragment; 4 | 5 | /** 6 | * User: mcxiaoke 7 | * Date: 16/1/29 8 | * Time: 21:43 9 | */ 10 | public class JavaFragmentV4 extends Fragment { 11 | 12 | public void test() { 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaLayout.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.widget.LinearLayout; 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/29 10 | * Time: 21:43 11 | */ 12 | public class JavaLayout extends LinearLayout { 13 | public JavaLayout(final Context context) { 14 | super(context); 15 | } 16 | 17 | public JavaLayout(final Context context, final AttributeSet attrs) { 18 | super(context, attrs); 19 | } 20 | 21 | 22 | public void test() { 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaService.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.app.IntentService; 4 | import android.content.Intent; 5 | 6 | /** 7 | * User: mcxiaoke 8 | * Date: 16/1/29 9 | * Time: 21:44 10 | */ 11 | public class JavaService extends IntentService { 12 | 13 | public JavaService() { 14 | super("JavaService"); 15 | } 16 | 17 | @Override 18 | protected void onHandleIntent(final Intent intent) { 19 | 20 | } 21 | 22 | public void test() { 23 | 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaSimpleClass.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/29 6 | * Time: 21:45 7 | */ 8 | public class JavaSimpleClass { 9 | 10 | public void test() { 11 | 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /samples/src/main/java/com/mcxiaoke/koi/samples/JavaView.java: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples; 2 | 3 | import android.content.Context; 4 | import android.util.AttributeSet; 5 | import android.widget.ImageView; 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/29 10 | * Time: 21:44 11 | */ 12 | public class JavaView extends ImageView { 13 | public JavaView(final Context context) { 14 | super(context); 15 | } 16 | 17 | public JavaView(final Context context, final AttributeSet attrs) { 18 | super(context, attrs); 19 | } 20 | 21 | public void test() { 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/AdapterSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.app.Activity 4 | import android.os.Bundle 5 | import com.mcxiaoke.koi.ext.quickAdapterOf 6 | import com.mcxiaoke.koi.samples.R 7 | import kotlinx.android.synthetic.main.activity_main.* 8 | 9 | /** 10 | * Author: mcxiaoke 11 | * Date: 2016/2/2 23:26 12 | */ 13 | 14 | class QuickAdapterSample : Activity() { 15 | 16 | override fun onCreate(savedInstanceState: Bundle?) { 17 | super.onCreate(savedInstanceState) 18 | setContentView(R.layout.activity_main) 19 | } 20 | 21 | // easy way to create array adapter 22 | fun adapterFunctions() { 23 | listView.adapter = quickAdapterOf( 24 | android.R.layout.simple_list_item_2, 25 | (1..100).map { "List Item No.$it" }) 26 | { binder, data -> 27 | binder.setText(android.R.id.text1, data) 28 | binder.setText(android.R.id.text2, "Index: ${binder.position}") 29 | } 30 | 31 | val adapter2 = quickAdapterOf(android.R.layout.simple_list_item_1) { 32 | binder, data -> 33 | binder.setText(android.R.id.text1, data) 34 | } 35 | adapter2.addAll(listOf("Cat", "Dog", "Rabbit")) 36 | 37 | val adapter3 = quickAdapterOf(android.R.layout.simple_list_item_1, 38 | arrayOf(1, 2, 3, 4, 5, 6)) { 39 | binder, data -> 40 | binder.setText(android.R.id.text1, "Item Number: $data") 41 | } 42 | 43 | val adapter4 = quickAdapterOf(android.R.layout.simple_list_item_1, 44 | setOf(22, 33, 4, 5, 6, 8, 8, 8)) { 45 | binder, data -> 46 | binder.setText(android.R.id.text1, "Item Number: $data") 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/AsyncSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import com.mcxiaoke.koi.async.* 4 | import java.util.concurrent.Executors 5 | 6 | /** 7 | * Author: mcxiaoke 8 | * Date: 2016/2/3 9:01 9 | */ 10 | class AsyncFunctionsSample { 11 | private val intVal = 1000 12 | private var strVal: String? = null 13 | 14 | // async functions with context check 15 | // internal using isContextAlive 16 | // context alive: 17 | // !Activity.isFinishing 18 | // Fragment.isAdded 19 | // !Detachable.isDetached 20 | // 21 | // available in any where 22 | // using in Activity/Fragment better 23 | fun asyncSafeFunction1() { 24 | // safe means context alive check 25 | // async 26 | asyncSafe { 27 | print("action executed only if context alive ") 28 | // if you want get caller context 29 | // maybe null 30 | val ctx = getCtx() 31 | // you can also using outside variables 32 | // not recommended 33 | // if context is Activity or Fragment 34 | // may cause memory leak 35 | print("outside value, $intVal $strVal") 36 | 37 | // you can using mainThreadSafe here 38 | // like a callback 39 | mainThreadSafe { 40 | // also with context alive check 41 | // if context dead, not executed 42 | print("code here executed in main thread") 43 | } 44 | // if you don't want context check, using mainThread{} 45 | mainThread { 46 | // no context check 47 | print("code here executed in main thread") 48 | } 49 | } 50 | // if your result or error is nullable 51 | // using asyncSafe2, just as asyncSafe 52 | // but type of result and error is T?, Throwable? 53 | } 54 | 55 | fun asyncSafeFunction2() { 56 | 57 | // async with callback 58 | asyncSafe( 59 | { 60 | print("action executed in async thread") 61 | listOf(1, 2, 3, 4, 5) 62 | }, 63 | { result, error -> 64 | // in main thread 65 | print("callback executed in main thread") 66 | }) 67 | } 68 | 69 | fun asyncSafeFunction3() { 70 | // async with success/failure callback 71 | asyncSafe( 72 | { 73 | print("action executed in async thread") 74 | "this string is result of the action" 75 | // throw RuntimeException("action error") 76 | }, 77 | { result -> 78 | // if action success with no exception 79 | print("success callback in main thread result:$result") 80 | }, 81 | { error -> 82 | // if action failed with exception 83 | print("failure callback in main thread, error:$error") 84 | }) 85 | } 86 | 87 | fun asyncSafeFunction4() { 88 | val executor = Executors.newFixedThreadPool(4) 89 | asyncSafe(executor) { 90 | print("action executed in async thread") 91 | mainThreadSafe { 92 | print("code here executed in main thread") 93 | } 94 | } 95 | } 96 | 97 | 98 | // if you don't want context check 99 | // using asyncUnsafe series functions 100 | // just replace asyncSafe with asyncUnsafe 101 | fun asyncUnsafeFunctions() { 102 | // async 103 | asyncUnsafe { 104 | print("action executed with no context check ") 105 | // may cause memory leak 106 | print("outside value, $intVal $strVal") 107 | 108 | mainThread { 109 | // no context check 110 | print("code here executed in main thread") 111 | } 112 | } 113 | } 114 | 115 | // async functions with delay 116 | // with context check 117 | // if context died, not executed 118 | // others just like asyncSafe 119 | fun asyncDelayFunctions() { 120 | // usage see asyncSafe 121 | asyncDelay(5000) { 122 | print("action executed after 5000ms only if context alive ") 123 | 124 | // you can using mainThreadSafe here 125 | // like a callback 126 | mainThreadSafe { 127 | // also with context alive check 128 | // if context dead, not executed 129 | print("code here executed in main thread") 130 | } 131 | // if you don't want context check, using mainThread{} 132 | mainThread { 133 | // no context check 134 | print("code here executed in main thread") 135 | } 136 | } 137 | } 138 | 139 | 140 | } 141 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/BundleSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.app.Activity 4 | import android.os.Bundle 5 | import com.mcxiaoke.koi.ext.Bundle 6 | 7 | /** 8 | * Author: mcxiaoke 9 | * Date: 2016/2/2 20:48 10 | */ 11 | 12 | class BundleExtensionSample { 13 | 14 | 15 | // available in any where 16 | fun bundleExtension() { 17 | // easy way to create bundle 18 | val bundle = Bundle { 19 | putString("key", "value") 20 | putInt("int", 12345) 21 | putBoolean("boolean", false) 22 | putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5)) 23 | putStringArrayList("strings", arrayListOf("Hello", "World", "Cat")) 24 | } 25 | 26 | // equal to using with 27 | val bundle2 = Bundle() 28 | with(bundle2) { 29 | putString("key", "value") 30 | putInt("int", 12345) 31 | putBoolean("boolean", false) 32 | putIntArray("intArray", intArrayOf(1, 2, 3, 4, 5)) 33 | putStringArrayList("strings", arrayListOf("Hello", "World", "Cat")) 34 | } 35 | } 36 | } -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/CollectionSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import com.mcxiaoke.koi.ext.* 4 | 5 | /** 6 | * Author: mcxiaoke 7 | * Date: 2016/2/2 20:53 8 | */ 9 | 10 | class CollectionExtensionSample { 11 | 12 | fun collectionToString() { 13 | val pets = listOf("Cat", "Dog", "Rabbit", "Fish") 14 | // list to string, delimiter is space 15 | val string1 = pets.asString(delim = " ") // "Cat Dog Rabbit Fish" 16 | // default delimiter is comma 17 | val string2 = pets.asString() // "Cat,Dog,Rabbit,Fish" 18 | val numbers = arrayOf(2016, 2, 2, 20, 57, 40) 19 | // array to string, default delimiter is comma 20 | val string3 = numbers.asString() // "2016,2,2,20,57,40" 21 | // array to string, delimiter is - 22 | val string4 = numbers.asString(delim = "-") // 2016-2-2-20-57-40 23 | // using Kotlin stdlib 24 | val s1 = pets.joinToString() 25 | val s2 = numbers.joinToString(separator = "-", prefix = "<", postfix = ">") 26 | } 27 | 28 | fun mapToString() { 29 | val map = mapOf( 30 | "John" to 30, 31 | "Smith" to 50, 32 | "Alice" to 22 33 | ) 34 | // default delimiter is , 35 | val string1 = map.asString() // "John=30,Smith=50,Alice=22" 36 | // using delimiter / 37 | val string2 = map.asString(delim = "/") // "John=30/Smith=50/Alice=22" 38 | // using stdlib 39 | map.asSequence().joinToString { "${it.key}=${it.value}" } 40 | } 41 | 42 | fun appendAndPrepend() { 43 | val numbers = (1..6).toMutableList() 44 | println(numbers.joinToString()) // "1, 2, 3, 4, 5, 6, 7" 45 | numbers.head() // .dropLast(1) 46 | numbers.tail() //.drop(1) 47 | val numbers2 = 100.appendTo(numbers) // 48 | val numbers3 = 2016.prependTo(numbers) 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/ContextSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import android.app.IntentService 6 | import android.app.Service 7 | import android.content.Context 8 | import android.content.Intent 9 | import android.net.Uri 10 | import android.os.Bundle 11 | import android.os.IBinder 12 | import android.util.Log 13 | import android.view.View 14 | import android.view.ViewGroup 15 | import android.widget.TextView 16 | import com.mcxiaoke.koi.KoiConfig 17 | import com.mcxiaoke.koi.samples.app.MainActivity 18 | import com.mcxiaoke.koi.ext.* 19 | import com.mcxiaoke.koi.log.* 20 | import java.io.File 21 | 22 | /** 23 | * Author: mcxiaoke 24 | * Date: 2016/2/2 20:38 25 | */ 26 | 27 | class ActivityExtensionSample : Activity() { 28 | 29 | // available for Activity 30 | fun activityExtensions() { 31 | val act = getActivity() // Activity 32 | act.restart() // restart Activity 33 | val app = act.getApp() // Application 34 | val app2 = act.application // Application 35 | val textView = act.find(android.R.id.text1) 36 | } 37 | 38 | // available for Context 39 | fun toastExtensions() { 40 | // available in Activity/Fragment/Service/Context 41 | toast(R.string.app_name) 42 | toast("this is a toast") 43 | longToast(R.string.app_name) 44 | longToast("this is a long toast") 45 | } 46 | } 47 | 48 | class FragmentExtensionSample : Fragment() { 49 | 50 | // available for Fragment 51 | fun fragmentExtensions() { 52 | val act = activity // Activity 53 | val app = getApp() // Application 54 | val textView = find(android.R.id.text1) // view.findViewById 55 | val imageView = find(android.R.id.icon1) // view.findViewById 56 | } 57 | } 58 | 59 | class ContextExtensionSample : Activity() { 60 | 61 | // available for Context 62 | fun inflateLayout() { 63 | val view1 = inflate(R.layout.activity_main) 64 | val viewGroup = view1 as ViewGroup 65 | val view2 = inflate(android.R.layout.activity_list_item, viewGroup, false) 66 | } 67 | 68 | 69 | // available for Context 70 | fun miscExtensions() { 71 | val hasCamera = hasCamera() 72 | 73 | mediaScan(Uri.parse("file:///sdcard/Pictures/koi/cat.png")) 74 | addToMediaStore(File("/sdcard/Pictures/koi/cat.png")) 75 | 76 | val batteryStatusIntent = getBatteryStatus() 77 | val colorValue = getResourceValue(android.R.color.darker_gray) 78 | } 79 | 80 | // available for Context 81 | fun intentExtensions() { 82 | val extras = Bundle { putString("key", "value") } 83 | val intent1 = newIntent() 84 | val intent2 = newIntent(Intent.FLAG_ACTIVITY_NEW_TASK, extras) 85 | } 86 | 87 | // available for Activity 88 | fun startActivityExtensions() { 89 | startActivity() 90 | // equal to 91 | startActivity(Intent(this, MainActivity::class.java)) 92 | 93 | startActivity(Intent.FLAG_ACTIVITY_SINGLE_TOP, Bundle()) 94 | startActivity(Bundle()) 95 | 96 | startActivityForResult(100) 97 | startActivityForResult(Bundle(), 100) 98 | startActivityForResult(200, Intent.FLAG_ACTIVITY_CLEAR_TOP) 99 | } 100 | 101 | // available for Context 102 | fun startServiceExtensions() { 103 | startService() 104 | startService(Bundle()) 105 | } 106 | 107 | // available for Context 108 | fun networkExtensions() { 109 | val name = networkTypeName() 110 | val operator = networkOperator() 111 | val type = networkType() 112 | val wifi = isWifi() 113 | val mobile = isMobile() 114 | val connected = isConnected() 115 | } 116 | 117 | // available for Context 118 | fun notificationExtensions() { 119 | // easy way using Notification.Builder 120 | val notification = newNotification() { 121 | this.setColor(0x0099cc) 122 | .setAutoCancel(true) 123 | .setContentTitle("Notification Title") 124 | .setContentText("Notification Message Text") 125 | .setDefaults(0) 126 | .setGroup("koi") 127 | .setVibrate(longArrayOf(1, 0, 0, 1)) 128 | .setSubText("this is a sub title") 129 | .setSmallIcon(android.R.drawable.ic_dialog_info) 130 | .setLargeIcon(null) 131 | } 132 | } 133 | 134 | // available for Context 135 | fun packageExtensions() { 136 | val isYoutubeInstalled = isAppInstalled("com.google.android.youtube") 137 | val isMainProcess = isMainProcess() 138 | val disabled = isComponentDisabled(MainActivity::class.java) 139 | enableComponent(MainActivity::class.java) 140 | 141 | val sig = getPackageSignature() 142 | val sigString = getSignature() 143 | println(dumpSignature()) 144 | } 145 | 146 | // available for Context 147 | // easy way to get system service, no cast 148 | fun systemServices() { 149 | val wm = getWindowService() 150 | val tm = getTelephonyManager() 151 | val nm = getNotificationManager() 152 | val cm = getConnectivityManager() 153 | val am = getAccountManager() 154 | val acm = getActivityManager() 155 | val alm = getAlarmManager() 156 | val imm = getInputMethodManager() 157 | val inflater = getLayoutService() 158 | val lm = getLocationManager() 159 | val wifi = getWifiManager() 160 | } 161 | 162 | // available for Context 163 | fun logExtensions() { 164 | KoiConfig.logEnabled = true //default is false 165 | // true == Log.VERBOSE 166 | // false == Log.ASSERT 167 | // optional 168 | KoiConfig.logLevel = Log.VERBOSE // default is Log.ASSERT 169 | // 170 | 171 | logv("log functions available in Context") //Log.v 172 | logd("log functions available in Context") //Log.d 173 | logi("log functions available in Context") //Log.i 174 | logw("log functions available in Context") //Log.w 175 | loge("log functions available in Context") //Log.e 176 | logf("log functions available in Context") //Log.wtf 177 | 178 | // support lazy evaluated message 179 | logv { "lazy eval message lambda" } //Log.v 180 | logd { "lazy eval message lambda" } //Log.d 181 | logi { "lazy eval message lambda" } //Log.i 182 | logw { "lazy eval message lambda" } //Log.w 183 | loge { "lazy eval message lambda" } //Log.e 184 | logf { "lazy eval message lambda" } //Log.wtf 185 | } 186 | } 187 | 188 | // sample service 189 | class BackgroundService : IntentService("background") { 190 | 191 | override fun onHandleIntent(intent: Intent?) { 192 | throw UnsupportedOperationException() 193 | } 194 | 195 | } 196 | 197 | 198 | 199 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/CoreSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.app.Activity 4 | import android.app.Fragment 5 | import com.mcxiaoke.koi.async.* 6 | 7 | /** 8 | * Author: mcxiaoke 9 | * Date: 2016/2/3 8:44 10 | */ 11 | class AsyncCoreSample { 12 | 13 | // available in any where 14 | fun executorFunctions() { 15 | // global main handler 16 | val uiHandler1 = CoreExecutor.mainHandler 17 | // or using this function 18 | val uiHandler2 = koiHandler() 19 | 20 | // global executor service 21 | val executor = CoreExecutor.executor 22 | // or using this function 23 | val executor2 = koiExecutor() 24 | 25 | // create thread pool functions 26 | val pool1 = newCachedThreadPool("cached") 27 | val pool2 = newFixedThreadPool("fixed", 4) 28 | val pool3 = newSingleThreadExecutor("single") 29 | 30 | } 31 | 32 | // available in any where 33 | fun mainThreadFunctions() { 34 | //check current thread 35 | // call from any where 36 | val isMain = isMainThread() 37 | 38 | // execute in main thread 39 | mainThread { 40 | print("${(1..8).asSequence().joinToString()}") 41 | } 42 | 43 | // delay execute in main thread 44 | mainThreadDelay(3000) { 45 | print("execute after 3000 ms") 46 | } 47 | 48 | } 49 | 50 | // available in any where 51 | fun safeFunctions() { 52 | val context = this 53 | // check Activity/Fragment lifecycle 54 | val alive = isContextAlive(context) 55 | 56 | // isContextAlive function impl 57 | fun isContextAlive(context: T?): Boolean { 58 | return when (context) { 59 | null -> false 60 | is Activity -> !context.isFinishing 61 | is Fragment -> context.isAdded 62 | is android.support.v4.app.Fragment -> context.isAdded 63 | is Detachable -> !context.isDetached() 64 | else -> true 65 | } 66 | } 67 | 68 | fun func1() { 69 | print("func1") 70 | } 71 | // convert to safe function with context check 72 | // internal using isContextAlive 73 | val safeFun1 = safeFunction(::func1) 74 | 75 | // call function with context check 76 | // internal using isContextAlive 77 | safeExecute(::func1) 78 | 79 | // direct use 80 | safeExecute { print("func1") } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/CursorSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.content.ContentValues 4 | import android.content.Context 5 | import android.database.sqlite.SQLiteDatabase 6 | import android.database.sqlite.SQLiteOpenHelper 7 | import com.mcxiaoke.koi.ext.* 8 | 9 | /** 10 | * Author: mcxiaoke 11 | * Date: 2016/2/2 21:10 12 | */ 13 | // sample data class 14 | data class UserInfo(val name: String, val age: Int, val bio: String?, val hasPet: Boolean) 15 | 16 | class CursorExtensionSample(context: Context, name: String, 17 | factory: SQLiteDatabase.CursorFactory?, version: Int) 18 | : SQLiteOpenHelper(context, name, factory, version) { 19 | 20 | override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { 21 | throw UnsupportedOperationException() 22 | } 23 | 24 | override fun onCreate(db: SQLiteDatabase?) { 25 | throw UnsupportedOperationException() 26 | } 27 | 28 | // available for Cursor 29 | fun cursorValueExtensions() { 30 | val cursor = this.writableDatabase.query("table", null, null, null, null, null, null) 31 | cursor.moveToFirst() 32 | do { 33 | val intVal = cursor.intValue("column-a") 34 | val stringVal = cursor.stringValue("column-b") 35 | val longVal = cursor.longValue("column-c") 36 | val booleanValue = cursor.booleanValue("column-d") 37 | val doubleValue = cursor.doubleValue("column-e") 38 | val floatValue = cursor.floatValue("column-f") 39 | 40 | // no need to do like this, so verbose 41 | cursor.getInt(cursor.getColumnIndexOrThrow("column-a")) 42 | cursor.getString(cursor.getColumnIndexOrThrow("column-b")) 43 | } while (cursor.moveToNext()) 44 | } 45 | 46 | // available for Cursor 47 | // transform cursor to model object 48 | fun cursorToModels() { 49 | val where = " age>? " 50 | val whereArgs = arrayOf("20") 51 | val cursor = this.readableDatabase.query("users", null, where, whereArgs, null, null, null) 52 | val users1 = cursor.map { 53 | UserInfo( 54 | stringValue("name"), 55 | intValue("age"), 56 | stringValue("bio"), 57 | booleanValue("pet_flag")) 58 | } 59 | 60 | // or using mapAndClose 61 | val users2 = cursor.mapAndClose { 62 | UserInfo( 63 | stringValue("name"), 64 | intValue("age"), 65 | stringValue("bio"), 66 | booleanValue("pet_flag")) 67 | } 68 | 69 | // or using Cursor?mapTo(collection, transform()) 70 | } 71 | 72 | 73 | // available for SQLiteDatabase and SQLiteOpenHelper 74 | // auto apply transaction to db operations 75 | fun inTransaction() { 76 | val db = this.writableDatabase 77 | val values = ContentValues() 78 | 79 | // or db.transaction 80 | transaction { 81 | db.execSQL("insert into users (?,?,?) (1,2,3)") 82 | db.insert("users", null, values) 83 | } 84 | // equal to 85 | db.beginTransaction() 86 | try { 87 | db.execSQL("insert into users (?,?,?) (1,2,3)") 88 | db.insert("users", null, values) 89 | db.setTransactionSuccessful() 90 | } finally { 91 | db.endTransaction() 92 | } 93 | } 94 | 95 | } -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/DateSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import com.mcxiaoke.koi.ext.* 4 | import java.text.SimpleDateFormat 5 | import java.util.* 6 | 7 | /** 8 | * Author: mcxiaoke 9 | * Date: 2016/2/2 21:31 10 | */ 11 | class DateExtensionSample { 12 | 13 | 14 | // available in any where 15 | fun dateSample() { 16 | val nowString = dateNow() 17 | val date = dateParse("2016-02-02 20:30:45") 18 | val dateStr1 = date.asString() 19 | val dateStr2 = date.asString(SimpleDateFormat("yyyyMMdd.HHmmss")) 20 | val dateStr3 = date.asString("yyyy-MM-dd-HH-mm-ss") 21 | 22 | // easy way to get timestamp 23 | val timestamp1 = timestamp() 24 | // equal to 25 | val timestamp2 = System.currentTimeMillis() 26 | val dateStr4 = timestamp1.asDateString() 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/HandlerSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.os.Handler 4 | import com.mcxiaoke.koi.ext.* 5 | 6 | /** 7 | * Author: mcxiaoke 8 | * Date: 2016/2/2 21:37 9 | */ 10 | 11 | class HandlerExtensionSample { 12 | 13 | // available for Handler 14 | // short name for functions 15 | fun handlerFunctions() { 16 | val handler = Handler() 17 | 18 | handler.atNow { print("perform action now") } 19 | // equal to 20 | handler.post { print("perform action now") } 21 | 22 | handler.atFront { print("perform action at first") } 23 | // equal to 24 | handler.postAtFrontOfQueue { print("perform action at first") } 25 | 26 | 27 | handler.atTime(timestamp() + 5000, { print("perform action after 5s") }) 28 | // equal to 29 | handler.postAtTime({ print("perform action after 5s") }, 5000) 30 | 31 | handler.delayed(3000, { print("perform action after 3s") }) 32 | // equal to 33 | handler.postDelayed({ print("perform action after 3s") }, 3000) 34 | 35 | // repeating actions 36 | handler.repeat(3000) { print("perform action indefinitely every 3s") } 37 | 38 | handler.repeat( 39 | delayMillis = 1000, 40 | startDelayMillis = 3000, 41 | repeatCount = 5 42 | ) { 43 | print("perform action 5 times every 3s starting 1s after initial call") 44 | } 45 | 46 | // cancels all pending messages and callbacks 47 | handler.cancelAll() 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/IOSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import com.mcxiaoke.koi.Encoding 4 | import com.mcxiaoke.koi.ext.* 5 | import java.io.* 6 | 7 | /** 8 | * Author: mcxiaoke 9 | * Date: 2016/2/2 21:52 10 | */ 11 | 12 | class IOExtensionSample { 13 | 14 | // available for Closeable 15 | fun closeableSample() { 16 | val input = FileInputStream(File("readme.txt")) 17 | try { 18 | val string = input.readString(Charsets.UTF_8) 19 | } catch(e: IOException) { 20 | e.printStackTrace() 21 | } finally { 22 | input.closeQuietly() 23 | } 24 | } 25 | 26 | // simple way, equal to closeableSample 27 | // InputStream.doSafe{} 28 | fun doSafeSample() { 29 | val input = FileInputStream(File("readme.txt")) 30 | input.doSafe { 31 | val string = readString(Charsets.UTF_8) 32 | } 33 | } 34 | 35 | 36 | // available for InputStream/Reader 37 | fun readStringAndList1() { 38 | val input = FileInputStream(File("readme.txt")) 39 | try { 40 | val reader = input.reader(Charsets.UTF_8) 41 | 42 | val string1 = input.readString(Charsets.UTF_8) 43 | 44 | val list1 = input.readList() 45 | val list2 = input.readList(Charsets.UTF_8) 46 | 47 | } catch(e: IOException) { 48 | 49 | } finally { 50 | input.closeQuietly() 51 | } 52 | } 53 | 54 | // available for InputStream/Reader 55 | //equal to readStringAndList1 56 | fun readStringAndList2() { 57 | val input = FileInputStream(File("readme.txt")) 58 | input.doSafe { 59 | val reader = reader(Charsets.UTF_8) 60 | 61 | val string1 = readString(Charsets.UTF_8) 62 | 63 | val list1 = readList() 64 | val list2 = readList(Charsets.UTF_8) 65 | } 66 | } 67 | 68 | fun writeStringAndList() { 69 | val output = FileOutputStream("output.txt") 70 | output.doSafe { 71 | output.writeString("hello, world") 72 | output.writeString("你好,世界", charset = Charsets.UTF_8) 73 | 74 | val list1 = listOf(1, 2, 3, 4, 5) 75 | val list2 = (1..8).map { "Item No.$it" } 76 | output.writeList(list1, charset = Charsets.UTF_8) 77 | output.writeList(list2) 78 | } 79 | } 80 | 81 | fun fileReadWrite() { 82 | val directory = File("/Users/koi/workspace") 83 | val file = File("some.txt") 84 | 85 | val text1 = file.readText() 86 | val text2 = file.readString(Charsets.UTF_8) 87 | val list1 = file.readList() 88 | val list2 = file.readLines(Charsets.UTF_8) 89 | 90 | file.writeText("hello, world") 91 | file.writeList(list1) 92 | file.writeList(list2, Charsets.UTF_8) 93 | 94 | val v1 = file.relativeToOrNull(directory) 95 | val v2 = file.toRelativeString(directory) 96 | 97 | // clean files in directory 98 | directory.clean() 99 | 100 | 101 | val file1 = File("a.txt") 102 | val file2 = File("b.txt") 103 | file1.copyTo(file2, overwrite = false) 104 | } 105 | 106 | } -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/MiscSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.os.Parcel 4 | import android.os.Parcelable 5 | import com.mcxiaoke.koi.HASH 6 | import com.mcxiaoke.koi.assert.throwIfEmpty 7 | import com.mcxiaoke.koi.assert.throwIfFalse 8 | import com.mcxiaoke.koi.assert.throwIfNull 9 | import com.mcxiaoke.koi.assert.throwIfTrue 10 | import com.mcxiaoke.koi.ext.* 11 | import com.mcxiaoke.koi.threadName 12 | import com.mcxiaoke.koi.utils.* 13 | 14 | /** 15 | * Author: mcxiaoke 16 | * Date: 2016/2/2 22:43 17 | */ 18 | class OtherExtensionSample { 19 | 20 | fun numberExtensions() { 21 | val number = 179325344324902187L 22 | println(number.readableByteCount()) 23 | 24 | val bytes = byteArrayOf(1, 7, 0, 8, 9, 4, 125) 25 | println(bytes.hexString()) 26 | } 27 | 28 | // available for String 29 | fun stringExtensions() { 30 | val string = "hello, little cat!" 31 | val quotedString = string.quote() 32 | val isBlank = string.isBlank() 33 | val hexBytes = string.toHexBytes() 34 | val s1 = string.trimAllWhitespace() 35 | val c = string.containsWhitespace() 36 | 37 | val url = "https://github.com/mcxiaoke/kotlin-koi?year=2016&encoding=utf8&a=b#changelog" 38 | val urlNoQuery = url.withoutQuery() 39 | 40 | val isNameSafe = url.isNameSafe() 41 | val fileName = url.toSafeFileName() 42 | val queries = url.toQueries() 43 | 44 | val path = "/Users/koi/workspace/String.kt" 45 | val baseName = path.fileNameWithoutExtension() 46 | val extension = path.fileExtension() 47 | val name = path.fileName() 48 | } 49 | 50 | fun threadFunctions() { 51 | val tn = threadName() 52 | } 53 | 54 | // available in any where 55 | fun cryptoFunctions() { 56 | val md5 = HASH.md5("hello, world") 57 | val sha1 = HASH.sha1("hello, world") 58 | val sha256 = HASH.sha256("hello, world") 59 | 60 | } 61 | 62 | // available in any where 63 | fun apiLevelFunctions() { 64 | // Build.VERSION.SDK_INT 65 | val v = currentVersion() 66 | val ics = icsOrNewer() 67 | val kk = kitkatOrNewer() 68 | val bkk = beforeKitkat() 69 | val lol = lollipopOrNewer() 70 | val mar = marshmallowOrNewer() 71 | } 72 | 73 | // available in any where 74 | fun deviceSample() { 75 | val a = isLargeHeap 76 | val b = noSdcard() 77 | val c = noFreeSpace(needSize = 10 * 1024 * 1024L) 78 | val d = freeSpace() 79 | } 80 | 81 | // available in any where 82 | // null and empty check 83 | fun preconditions() { 84 | throwIfEmpty(listOf(), "collection is null or empty") 85 | throwIfNull(null, "object is null") 86 | throwIfTrue(currentVersion() == 10, "result is true") 87 | throwIfFalse(currentVersion() < 4, "result is false") 88 | } 89 | 90 | } 91 | 92 | // easy way to create Android Parcelable class 93 | data class Person(val name: String, val age: Int) : Parcelable { 94 | 95 | override fun writeToParcel(dest: Parcel, flags: Int) { 96 | dest.writeString(name) 97 | dest.writeInt(age) 98 | } 99 | 100 | override fun describeContents(): Int = 0 101 | 102 | protected constructor(p: Parcel) : this(name = p.readString(), age = p.readInt()) { 103 | } 104 | 105 | companion object { 106 | // using createParcel 107 | @JvmField val CREATOR = createParcel { Person(it) } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/ViewSample.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples 2 | 3 | import android.app.Activity 4 | import android.content.Context 5 | import android.view.KeyEvent 6 | import android.view.MotionEvent 7 | import android.view.View 8 | import android.widget.* 9 | import com.mcxiaoke.koi.ext.* 10 | import org.jetbrains.anko.onKey 11 | import org.jetbrains.anko.onTouch 12 | 13 | /** 14 | * Author: mcxiaoke 15 | * Date: 2016/2/2 23:06 16 | */ 17 | 18 | class ViewExtensionSample1 : Activity() { 19 | 20 | fun viewListeners1() { 21 | val view = View(this) 22 | // View.OnClickListener 23 | view.onClick { print("view clicked") } 24 | // View.OnLongClickListener 25 | view.onLongClick { print("view long clicked");false } 26 | // View.OnKeyListener 27 | view.onKeyEvent { view, keyCode, event -> 28 | print("keyEvent: action:${event.action} code:$keyCode") 29 | false 30 | } 31 | // View.OnTouchListener 32 | view.onTouchEvent { view, event -> 33 | when (event.actionMasked) { 34 | MotionEvent.ACTION_DOWN -> print("touch down") 35 | MotionEvent.ACTION_UP -> print("touch up") 36 | MotionEvent.ACTION_MOVE -> print("touch move") 37 | } 38 | false 39 | } 40 | // View.OnFocusChangeListener 41 | view.onFocusChange { view, hasFocus -> 42 | print("focus changed = $hasFocus") 43 | } 44 | } 45 | 46 | fun viewListeners2() { 47 | // TextWatcher 48 | val editText = EditText(this) 49 | editText.onTextChange { text, start, before, count -> 50 | print("text changed: $text") 51 | } 52 | 53 | // OnCheckedChangeListener 54 | val checkBox = CheckBox(this) 55 | checkBox.onCheckedChanged { button, isChecked -> 56 | print("CheckBox value changed:$isChecked") 57 | } 58 | 59 | // OnSeekBarChangeListener 60 | val seekBar = SeekBar(this) 61 | seekBar.onProgressChanged { seekBar, progress, fromUser -> 62 | print("seekBar progress: $progress") 63 | } 64 | } 65 | 66 | fun listViewListeners() { 67 | val listView = ListView(this) 68 | // OnItemClickListener 69 | listView.onItemClick { parent, view, position, id -> 70 | print("onItemClick: position=$position") 71 | } 72 | // OnScrollListener 73 | listView.onScrollChanged { view, scrollState -> 74 | print("scroll state changed") 75 | } 76 | } 77 | } 78 | 79 | class ViewExtensionSample2(ctx: Context) : View(ctx) { 80 | 81 | 82 | // available for View 83 | fun viewSample() { 84 | val w = dm.widthPixels 85 | val h = dm.heightPixels 86 | 87 | val v1 = 32.5f 88 | val dp1 = v1.pxToDp() 89 | 90 | val v2 = 24f 91 | val px1 = v2.dpToPx() 92 | 93 | val dp2 = pxToDp(56) 94 | val px2 = dpToPx(32) 95 | 96 | val dp3 = 72.pxToDp() 97 | val px3 = 48.dpToPx() 98 | 99 | hideSoftKeyboard() 100 | 101 | val editText = EditText(context) 102 | editText.showSoftKeyboard() 103 | editText.toggleSoftKeyboard() 104 | } 105 | 106 | } -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/app/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.app 2 | 3 | import android.content.Context 4 | import android.os.Bundle 5 | import android.support.v7.app.AppCompatActivity 6 | import com.mcxiaoke.koi.async.* 7 | import com.mcxiaoke.koi.ext.quickAdapterOf 8 | import com.mcxiaoke.koi.log.logd 9 | import com.mcxiaoke.koi.log.logv 10 | import com.mcxiaoke.koi.samples.R 11 | import kotlinx.android.synthetic.main.activity_main.* 12 | import org.jetbrains.anko.async 13 | import org.jetbrains.anko.uiThread 14 | import java.lang.ref.WeakReference 15 | import java.util.concurrent.Executors 16 | 17 | /** 18 | * User: mcxiaoke 19 | * Date: 15/11/5 20 | * Time: 15:43 21 | */ 22 | class MainActivity : AppCompatActivity() { 23 | companion object { 24 | const val TAG = "MainActivity" 25 | } 26 | 27 | override fun onCreate(savedInstanceState: Bundle?) { 28 | super.onCreate(savedInstanceState) 29 | logv("onCreate()") 30 | setContentView(R.layout.activity_main) 31 | listView.adapter = quickAdapterOf( 32 | android.R.layout.simple_list_item_2, 33 | (1..100).map { "List Item No.$it" }) 34 | { binder, data -> 35 | binder.setText(android.R.id.text1, data) 36 | binder.setText(android.R.id.text2, "Index: ${binder.position}") 37 | } 38 | logv("onCreate() ${listView.adapter}") 39 | testSafe() 40 | testAsync() 41 | testInline() 42 | } 43 | 44 | fun createAction(name: String): () -> Unit { 45 | return { logv("createAction() name:$name") } 46 | } 47 | 48 | fun testInline() { 49 | var weakCtx = WeakContext(WeakReference(this)) 50 | weakCtx.safe { 51 | listOf(1, 2, 3, 4, 5) 52 | } 53 | } 54 | 55 | fun testSafe() { 56 | asyncUnsafe { 57 | logv("testSafe() async action start") 58 | Thread.sleep(5000) 59 | logv("testSafe() async action end") 60 | safeFunction(createAction("safeFunc1"))() 61 | safeExecute(createAction("safe1")) 62 | mainThread { 63 | safeExecute(createAction("safe2")) 64 | safeFunction(createAction("safeFunc2"))() 65 | } 66 | mainThread { 67 | logv("testSafe() mainThreadSafe") 68 | } 69 | } 70 | } 71 | 72 | fun testAsync() { 73 | async() { 74 | logv("async action") 75 | Thread.sleep(3000) 76 | uiThread { logv("async callback $it") } 77 | } 78 | asyncSafe { 79 | logv("asyncSafe1 action") 80 | Thread.sleep(3000) 81 | mainThreadSafe { logv("asyncSafe1 callback $it") } 82 | } 83 | val pool = newCachedThreadPool("cat") 84 | asyncSafe(pool) { 85 | logv("asyncSafe2 action") 86 | Thread.sleep(3000) 87 | mainThreadSafe { 88 | logv("asyncSafe2 callback $it") 89 | } 90 | } 91 | asyncSafe { 92 | logv("asyncSafe3 action") 93 | Thread.sleep(3000) 94 | mainThreadSafe { 95 | logv("asyncSafe3 callback $it") 96 | } 97 | } 98 | // FIXME 99 | // 1.0.0-beta-4589 100 | // inline functions compile error 101 | // https://youtrack.jetbrains.com/issue/KT-10137 102 | asyncSafe( 103 | { 104 | logd("asyncSafeAction1") 105 | Thread.sleep(6000) 106 | listOf(1, 2, 3, 4, 5) 107 | }, 108 | { r, e -> 109 | logd("asyncSafeCallback1:$r $e") 110 | } 111 | ) 112 | asyncSafe( 113 | { 114 | logd("asyncSafeAction2") 115 | listOf(1, 2, 3, 4, 5) 116 | Thread.sleep(6000) 117 | throw RuntimeException("asyncSafe") 118 | }, 119 | { r -> 120 | logd("asyncSafeCallback2: success:$r") 121 | } 122 | , 123 | { e -> 124 | logd("asyncSafeCallback2: failure:$e") 125 | } 126 | ) 127 | asyncSafe ( 128 | Executors.newSingleThreadExecutor(), 129 | { 130 | logd("asyncSafeAction3") 131 | Thread.sleep(6000) 132 | "asyncSafeAction3 Result" 133 | }, 134 | { r, e -> 135 | logd("asyncSafeCallback3:$r $e") 136 | } 137 | ) 138 | logd("asyncDelay add actions") 139 | asyncDelay(5000) { 140 | logv("asyncDelay0 5000 action") 141 | } 142 | asyncDelay(5000) { 143 | logv("asyncDelay1 5000 action") 144 | Thread.sleep(5000) 145 | mainThreadSafe { 146 | logv("asyncDelay1 5000 callback") 147 | } 148 | } 149 | asyncDelay(5000) { 150 | logv("asyncDelay2 5000 action") 151 | Thread.sleep(5000) 152 | mainThread { 153 | logv("asyncDelay2 5000 callback") 154 | } 155 | } 156 | 157 | asyncUnsafe { 158 | logv("asyncUnsafe 1 action") 159 | Thread.sleep(4000) 160 | mainThread { logv("asyncUnsafe 1 callback") } 161 | } 162 | asyncUnsafe(pool) { 163 | logv("asyncUnsafe 2 action") 164 | Thread.sleep(4000) 165 | mainThread { 166 | logv("asyncUnsafe 2 callback") 167 | } 168 | } 169 | asyncUnsafe { 170 | logv("asyncUnsafe 3 action") 171 | Thread.sleep(4000) 172 | mainThread { 173 | logv("asyncUnsafe 3 callback") 174 | } 175 | } 176 | asyncUnsafe( 177 | { 178 | logd("asyncUnsafe Action1") 179 | listOf(1, 2, 3, 4, 5) 180 | }, 181 | { r, e -> 182 | logd("asyncUnsafe Callback1:$r $e") 183 | } 184 | ) 185 | asyncUnsafe( 186 | { 187 | logd("asyncUnsafe Action2") 188 | listOf(1, 2, 3, 4, 5) 189 | throw RuntimeException("asyncSafe") 190 | }, 191 | { r -> 192 | logd("asyncUnsafe Callback2: success:$r") 193 | } 194 | , 195 | { e -> 196 | logd("asyncUnsafe Callback2: failure:$e") 197 | } 198 | ) 199 | asyncUnsafe ( 200 | Executors.newSingleThreadExecutor(), 201 | { 202 | logd("asyncUnsafe Action3") 203 | }, 204 | { r, e -> 205 | logd("asyncUnsafe Callback3:$r $e") 206 | } 207 | ) 208 | } 209 | 210 | } 211 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/app/MainApp.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.app 2 | 3 | import android.app.Application 4 | import com.mcxiaoke.koi.KoiConfig 5 | import kotlin.properties.Delegates 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 16/1/27 10 | * Time: 16:18 11 | */ 12 | class MainApp : Application() { 13 | 14 | companion object { 15 | var app: MainApp by Delegates.notNull() 16 | } 17 | 18 | var splashShowed = true 19 | 20 | override fun onCreate() { 21 | super.onCreate() 22 | app = this 23 | KoiConfig.logEnabled = true 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/app/MainFragment.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.app 2 | 3 | import android.os.Bundle 4 | import android.support.v4.app.Fragment 5 | import com.mcxiaoke.koi.async.asyncSafe 6 | import com.mcxiaoke.koi.async.mainThreadSafe 7 | import com.mcxiaoke.koi.log.logv 8 | 9 | /** 10 | * User: mcxiaoke 11 | * Date: 16/1/31 12 | * Time: 16:15 13 | */ 14 | class MainFragment : Fragment() { 15 | val flag = 0 16 | 17 | override fun onCreate(savedInstanceState: Bundle?) { 18 | super.onCreate(savedInstanceState) 19 | } 20 | 21 | fun testAsync() { 22 | asyncSafe { 23 | logv("Debug", "hello, world 1") 24 | 25 | mainThreadSafe { 26 | logv("Debug", "hello, world 2") 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/app/SplashActivity.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.app 2 | 3 | import android.os.Bundle 4 | import android.support.v7.app.AppCompatActivity 5 | import com.mcxiaoke.koi.ext.startActivity 6 | 7 | /** 8 | * User: mcxiaoke 9 | * Date: 15/11/5 10 | * Time: 15:43 11 | */ 12 | class SplashActivity : AppCompatActivity() { 13 | 14 | override fun onCreate(savedInstanceState: Bundle?) { 15 | super.onCreate(savedInstanceState) 16 | showMain() 17 | } 18 | 19 | private fun showMain() { 20 | startActivity() 21 | finish() 22 | } 23 | 24 | override fun onDestroy() { 25 | super.onDestroy() 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/json/Gson.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.json 2 | 3 | import com.google.gson.Gson 4 | import com.google.gson.JsonElement 5 | import com.google.gson.TypeAdapter 6 | import com.google.gson.reflect.TypeToken 7 | import com.google.gson.stream.JsonReader 8 | import com.google.gson.stream.JsonWriter 9 | import com.mcxiaoke.koi.samples.json.typeToken 10 | import java.io.Reader 11 | 12 | /** 13 | * User: mcxiaoke 14 | * Date: 16/1/30 15 | * Time: 11:43 16 | */ 17 | 18 | public inline fun Gson.getAdapter(): TypeAdapter 19 | = this.getAdapter(object : TypeToken() {}) 20 | 21 | public inline fun Gson.fromJson(json: String): T 22 | = this.fromJson(json, typeToken()) 23 | 24 | public inline fun Gson.fromJson(json: Reader): T 25 | = this.fromJson(json, typeToken()) 26 | 27 | public inline fun Gson.fromJson(json: JsonReader): T 28 | = this.fromJson(json, typeToken()) 29 | 30 | public inline fun Gson.fromJson(json: JsonElement): T 31 | = this.fromJson(json, typeToken()) 32 | 33 | public inline fun Gson.toJson(src: Any): String 34 | = this.toJson(src, typeToken()) 35 | 36 | public inline fun Gson.toJson(src: Any, writer: Appendable): Unit 37 | = this.toJson(src, typeToken(), writer) 38 | 39 | public inline fun Gson.toJson(src: Any, writer: JsonWriter): Unit 40 | = this.toJson(src, typeToken(), writer) -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/json/GsonBuilder.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.json 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/30 6 | * Time: 11:43 7 | */ 8 | 9 | import com.google.gson.* 10 | import com.google.gson.reflect.TypeToken 11 | import com.google.gson.stream.JsonReader 12 | import com.google.gson.stream.JsonWriter 13 | import java.lang.reflect.Type 14 | 15 | 16 | public inline fun typeToken(): Type 17 | = object : TypeToken() {}.type 18 | 19 | 20 | public fun typeAdapter(fRead: (JsonReader) -> T, fWrite: (JsonWriter, T) -> Unit): TypeAdapter 21 | = object : TypeAdapter() { 22 | override fun read(reader: JsonReader): T = fRead(reader) 23 | override fun write(writer: JsonWriter, value: T) = fWrite(writer, value) 24 | } 25 | 26 | public fun jsonSerializer(serializer: (src: T, type: Type, context: JsonSerializationContext) -> JsonElement): JsonSerializer 27 | = JsonSerializer { src, type, context -> serializer(src, type, context) } 28 | 29 | public fun simpleJsonSerializer(serializer: (src: T) -> JsonElement): JsonSerializer 30 | = JsonSerializer { src, type, context -> serializer(src) } 31 | 32 | public fun jsonDeserializer(deserializer: (json: JsonElement, type: Type, context: JsonDeserializationContext) -> T?): JsonDeserializer 33 | = JsonDeserializer { json, type, context -> deserializer(json, type, context) } 34 | 35 | public fun simpleJsonDeserializer(deserializer: (json: JsonElement) -> T?): JsonDeserializer 36 | = JsonDeserializer { json, type, context -> deserializer(json) } 37 | 38 | public fun instanceCreator(creator: (type: Type) -> T): InstanceCreator 39 | = InstanceCreator { creator(it) } 40 | 41 | 42 | public inline fun GsonBuilder.registerTypeAdapter(typeAdapter: Any): GsonBuilder 43 | = this.registerTypeAdapter(typeToken(), typeAdapter) 44 | 45 | public inline fun GsonBuilder.registerTypeHierarchyAdapter(typeAdapter: Any): GsonBuilder 46 | = this.registerTypeHierarchyAdapter(T::class.java, typeAdapter) 47 | 48 | 49 | public inline fun GsonBuilder.adapt(noinline fRead: (JsonReader) -> T, noinline fWrite: (JsonWriter, T) -> Unit): GsonBuilder 50 | = this.registerTypeAdapter(typeToken(), typeAdapter(fRead, fWrite)) 51 | 52 | public inline fun GsonBuilder.adaptHierarchy(noinline fRead: (JsonReader) -> T, noinline fWrite: (JsonWriter, T) -> Unit): GsonBuilder 53 | = this.registerTypeHierarchyAdapter(T::class.java, typeAdapter(fRead, fWrite)) 54 | 55 | 56 | public inline fun GsonBuilder.serialize(noinline serializer: (src: T, type: Type, context: JsonSerializationContext) -> JsonElement): GsonBuilder 57 | = this.registerTypeAdapter(typeToken(), jsonSerializer(serializer)) 58 | 59 | public inline fun GsonBuilder.serializeHierarchy(noinline serializer: (src: T, type: Type, context: JsonSerializationContext) -> JsonElement): GsonBuilder 60 | = this.registerTypeHierarchyAdapter(T::class.java, jsonSerializer(serializer)) 61 | 62 | public inline fun GsonBuilder.simpleSerialize(noinline serializer: (src: T) -> JsonElement): GsonBuilder 63 | = this.registerTypeAdapter(typeToken(), simpleJsonSerializer(serializer)) 64 | 65 | public inline fun GsonBuilder.simpleSerializeHierarchy(noinline serializer: (src: T) -> JsonElement): GsonBuilder 66 | = this.registerTypeHierarchyAdapter(T::class.java, simpleJsonSerializer(serializer)) 67 | 68 | 69 | public inline fun GsonBuilder.deserialize(noinline deserializer: (json: JsonElement, type: Type, context: JsonDeserializationContext) -> T?): GsonBuilder 70 | = this.registerTypeAdapter(typeToken(), jsonDeserializer(deserializer)) 71 | 72 | public inline fun GsonBuilder.deserializeHierarchy(noinline deserializer: (json: JsonElement, type: Type, context: JsonDeserializationContext) -> T?): GsonBuilder 73 | = this.registerTypeHierarchyAdapter(T::class.java, jsonDeserializer(deserializer)) 74 | 75 | public inline fun GsonBuilder.simpleDeserialize(noinline deserializer: (json: JsonElement) -> T?): GsonBuilder 76 | = this.registerTypeAdapter(typeToken(), simpleJsonDeserializer(deserializer)) 77 | 78 | public inline fun GsonBuilder.simpleDeserializeHierarchy(noinline deserializer: (json: JsonElement) -> T?): GsonBuilder 79 | = this.registerTypeHierarchyAdapter(T::class.java, simpleJsonDeserializer(deserializer)) 80 | 81 | 82 | public inline fun GsonBuilder.createInstances(noinline creator: (type: Type) -> T): GsonBuilder 83 | = this.registerTypeAdapter(typeToken(), instanceCreator(creator)) 84 | 85 | public inline fun GsonBuilder.createHierarchyInstances(noinline creator: (type: Type) -> T): GsonBuilder 86 | = this.registerTypeHierarchyAdapter(T::class.java, instanceCreator(creator)) -------------------------------------------------------------------------------- /samples/src/main/kotlin/com/mcxiaoke/koi/samples/tests/CoreTests.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.samples.tests 2 | 3 | import com.mcxiaoke.koi.assert.throwIfFalse 4 | import com.mcxiaoke.koi.assert.throwIfTrue 5 | import com.mcxiaoke.koi.async.asyncUnsafe 6 | import com.mcxiaoke.koi.async.isMainThread 7 | import com.mcxiaoke.koi.doIf 8 | import com.mcxiaoke.koi.log.logv 9 | 10 | /** 11 | * User: mcxiaoke 12 | * Date: 16/1/27 13 | * Time: 17:20 14 | */ 15 | 16 | class CoreTests { 17 | companion object { 18 | const val tag = "CoreTests" 19 | } 20 | 21 | fun runAllTests() { 22 | testAsync() 23 | testCondition() 24 | } 25 | 26 | fun testAsync() { 27 | asyncUnsafe { 28 | logv(tag, "async Thread:${Thread.currentThread()}") 29 | throwIfTrue(isMainThread()) 30 | } 31 | asyncUnsafe({ 32 | throwIfTrue(isMainThread()) 33 | logv(tag, "async action Thread:${Thread.currentThread()}") 34 | Thread.sleep(2000) 35 | }, { r, e -> 36 | logv(tag, "async callback Thread:${Thread.currentThread()}") 37 | throwIfFalse(isMainThread()) 38 | }) 39 | } 40 | 41 | fun testCondition() { 42 | doIf(true, { logv(tag, "true") }) 43 | doIf(false, { logv(tag, "false") }) 44 | doIf(null, { logv(tag, "null") }) 45 | 46 | doIf({ true }, { logv(tag, "{true}") }) 47 | doIf({ false }, { logv(tag, "{false}") }) 48 | doIf({ null }, { logv(tag, "{null}") }) 49 | 50 | val a: String? = null 51 | val b: String? = "Hello" 52 | val c: Int = 100 53 | val d: Long? = 100 54 | val e = null 55 | val f = false 56 | 57 | doIf(a, { logv(tag, "a") }) 58 | doIf(b, { logv(tag, "b") }) 59 | doIf(c, { logv(tag, "c") }) 60 | doIf(d, { logv(tag, "d") }) 61 | doIf(e, { logv(tag, "e") }) 62 | doIf(f, { logv(tag, "f") }) 63 | 64 | } 65 | } 66 | 67 | 68 | -------------------------------------------------------------------------------- /samples/src/main/res/drawable-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcxiaoke/kotlin-koi/58e548a531e1f66ce4bd8535058cf8d4173c5709/samples/src/main/res/drawable-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /samples/src/main/res/layout/activity_empty.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 13 | 14 | -------------------------------------------------------------------------------- /samples/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /samples/src/main/res/layout/activity_splash.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 16 | 17 | -------------------------------------------------------------------------------- /samples/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | KoiSamples 4 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':core' 2 | include ':async' 3 | include ':network' 4 | include ':ui' 5 | include ':samples' 6 | -------------------------------------------------------------------------------- /ui/build.gradle: -------------------------------------------------------------------------------- 1 | apply from: '../base.gradle' 2 | //apply from: 'https://coding.net/u/mcxiaoke/p/gradle-mvn-push/git/raw/master/gradle-mvn-push.gradle' 3 | 4 | 5 | //dependencies { 6 | // compile project(':core') 7 | //} 8 | -------------------------------------------------------------------------------- /ui/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Koi Library UI Widgets Module 2 | POM_ARTIFACT_ID=ui 3 | POM_PACKAGING=aar 4 | -------------------------------------------------------------------------------- /ui/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /ui/src/main/kotlin/com/mcxiaoke/koi/ui/UIConfig.kt: -------------------------------------------------------------------------------- 1 | package com.mcxiaoke.koi.ui 2 | 3 | /** 4 | * User: mcxiaoke 5 | * Date: 16/1/31 6 | * Time: 16:51 7 | */ 8 | --------------------------------------------------------------------------------