├── .gitignore ├── LICENSE ├── Readme.md ├── book.toml ├── code-files ├── Logger.java ├── android.gitignore └── mavencentral_push.gradle ├── deploy-to-github-pages.sh └── src ├── SUMMARY.md ├── adb-shell.md ├── android-aliases.md ├── android-examples.md ├── code-faster-using-keyboard.md ├── configure-as.md ├── extra-android-libraries-built-by-me.md ├── gradle-groovy-script-tips.md ├── gradle-kotlin-script-tips.md ├── helper-tools.md ├── img ├── accept_change.png ├── activityStateDiagram.jpeg ├── always_use_code_view.png ├── android_str_mismatch.jpg ├── apk_analyzer_ref.jpeg ├── are_notification_enabled.jpg ├── bookmarks_as.gif ├── bookmarks_mnemonic_as.gif ├── breakpoint_logs.jpg ├── build_single_config.jpg ├── dont_specify_buildtoolsversion.jpg ├── encode_special_1.gif ├── encode_special_2.png ├── encode_special_3.png ├── extract_native_libs.jpg ├── fold_line_like_this.gif ├── github_banner.png ├── group_recent_projects.jpg ├── inject_vars_in_manifest.png ├── live_template_wrapll_1.gif ├── live_template_wrapll_2.png ├── live_template_wrapll_3.png ├── making_methods_visible_for_testing.jpg ├── manifest-merged.png ├── mergetaginlayout.jpg ├── modified_default.png ├── multiline_todo_comment.png ├── proguard_rules_apk_analyzer.gif ├── quicklookup_def.gif ├── region_cmt.gif ├── region_cmt_template.gif ├── restore_default.png ├── running_hierarchy_viewer.jpg ├── selectiverun.gif ├── set_xml_as_preferred.jpg ├── testing_doze_mode.jpg ├── thread_annotations.jpg └── unmodified_default.png ├── introduction.md ├── learning-resources.md ├── make-better-choices-while-coding.md ├── misc.md ├── podcasts.md ├── scrcpy.md ├── tips-if-you-use-kotlin.md ├── tips-regarding-uiux.md ├── use-code-completion-in-as.md ├── use-plugins-in-as.md └── working-with-gradle-wrapper.md /.gitignore: -------------------------------------------------------------------------------- 1 | book/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2016 Nishant Srivastava 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | ![Image](src/img/github_banner.png) 2 | 3 | Cheatsheet about tips and tricks for Android Development. 4 | 5 | This is a simple set of tips and tricks regarding Android Development which I have gathered from various sources. It helps me direct other android devs in my community regarding stuff each android dev should know about. It is also there for me to keep track of anything I either learn on my own or from other sources now and then when browsing the internet. 6 | 7 | Contributions are always welcome, hoping people will help me in growing this. To contribute, simply open up a PR with the changes. 8 | 9 | Click here to navigate to the searchable book version 10 | 11 | 12 | ### Development 13 | 14 | #### Build Book 15 | ```mdbook build``` 16 | 17 | #### Build book and serve locally 18 | ```mdbook serve --open``` 19 | 20 | #### Build book and publish to Github Pages 21 | ```./deploy-to-github-pages.sh``` 22 | 23 | ### Show some ♥️ and 🌟 the repo to support the project 24 | 25 | [![GitHub stars](https://img.shields.io/github/stars/nisrulz/android-tips-tricks.svg?style=social&label=Star)](https://github.com/nisrulz/android-tips-tricks) [![GitHub forks](https://img.shields.io/github/forks/nisrulz/android-tips-tricks.svg?style=social&label=Fork)](https://github.com/nisrulz/android-tips-tricks/fork) [![GitHub watchers](https://img.shields.io/github/watchers/nisrulz/android-tips-tricks.svg?style=social&label=Watch)](https://github.com/nisrulz/android-tips-tricks) [![GitHub followers](https://img.shields.io/github/followers/nisrulz.svg?style=social&label=Follow)](https://github.com/nisrulz/android-tips-tricks) 26 | 27 | ### Featured in 28 | 29 | [![Android Weekly](https://img.shields.io/badge/Android%20Weekly-%23221-blue.svg)](http://androidweekly.net/issues/issue-221) [![AndroidDev Digest](https://img.shields.io/badge/AndroidDev%20Digest-%23110-blue.svg)](https://www.androiddevdigest.com/digest-110/) [![awesome-android](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/JStumpp/awesome-android#resources) 30 | 31 | **Also included in** 32 | 33 | - [Awesome Android Newsletter #Issue 16](https://android.libhunt.com/newsletter/16) 34 | 35 | #### Credits 36 | 37 | This curated cheatsheet includes tips and tricks that I have been following in my workflow as well as those being suggested/followed by other android devs worldwide.I have tried to add direct links wherever I could remember, giving people due credit who have explained the concepts. If you think I have missed any, then either send a PR or open an issue and I will fix it asap. 38 | 39 | If you appreciate my work, consider [buying me](https://www.paypal.me/nisrulz/5usd) a cup of ☕️ to keep me recharged 🤘🏼 [[PayPal](https://www.paypal.me/nisrulz/5usd)] 40 | 41 | [![Twitter Follow](https://img.shields.io/twitter/follow/nisrulz.svg?style=social)](https://twitter.com/nisrulz) 42 | 43 | 44 | [Apache Version 2.0 | Copyright 2016 Nishant Srivastava](LICENSE) 45 | -------------------------------------------------------------------------------- /book.toml: -------------------------------------------------------------------------------- 1 | [book] 2 | authors = ["Nishant Srivastava"] 3 | language = "en" 4 | multilingual = false 5 | src = "src" 6 | title = "Android Tips & Tricks" -------------------------------------------------------------------------------- /code-files/Logger.java: -------------------------------------------------------------------------------- 1 | package github.nisrulz.logger; 2 | 3 | import android.util.Log; 4 | 5 | public class Logger { 6 | 7 | private final String TAG; 8 | private final int priority; 9 | 10 | public static Logger withTag(String tag) { 11 | return new Logger(tag); 12 | } 13 | 14 | private Logger(String TAG) { 15 | this.TAG = TAG; 16 | this.priority = Log.DEBUG; // This could be ERROR / INFO / VERBOSE 17 | } 18 | 19 | public Logger log(String message) { 20 | if (BuildConfig.DEBUG) { 21 | Log.println(priority, TAG, message); 22 | } 23 | return this; 24 | } 25 | 26 | public void withCause(Exception cause) { 27 | if (BuildConfig.DEBUG) { 28 | Log.println(priority, TAG, Log.getStackTraceString(cause)); 29 | } 30 | } 31 | } -------------------------------------------------------------------------------- /code-files/android.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/java,macos,linux,gradle,windows,android,androidstudio 2 | 3 | ### Android ### 4 | # Built application files 5 | *.apk 6 | *.ap_ 7 | 8 | # Files for the ART/Dalvik VM 9 | *.dex 10 | 11 | # Java class files 12 | *.class 13 | 14 | # Generated files 15 | bin/ 16 | gen/ 17 | out/ 18 | 19 | # Gradle files 20 | .gradle/ 21 | build/ 22 | 23 | # Local configuration file (sdk path, etc) 24 | local.properties 25 | 26 | # Proguard folder generated by Eclipse 27 | proguard/ 28 | 29 | # Log Files 30 | *.log 31 | 32 | # Android Studio Navigation editor temp files 33 | .navigation/ 34 | 35 | # Android Studio captures folder 36 | captures/ 37 | 38 | # Intellij 39 | *.iml 40 | .idea/workspace.xml 41 | .idea/tasks.xml 42 | .idea/gradle.xml 43 | .idea/dictionaries 44 | .idea/libraries 45 | 46 | # Keystore files 47 | *.jks 48 | 49 | # External native build folder generated in Android Studio 2.2 and later 50 | .externalNativeBuild 51 | 52 | # Google Services (e.g. APIs or Firebase) 53 | google-services.json 54 | 55 | # Freeline 56 | freeline.py 57 | freeline/ 58 | freeline_project_description.json 59 | 60 | ### Android Patch ### 61 | gen-external-apklibs 62 | 63 | ### AndroidStudio ### 64 | # Covers files to be ignored for android development using Android Studio. 65 | 66 | # Built application files 67 | 68 | # Files for the ART/Dalvik VM 69 | 70 | # Java class files 71 | 72 | # Generated files 73 | 74 | # Gradle files 75 | .gradle 76 | 77 | # Signing files 78 | .signing/ 79 | 80 | # Local configuration file (sdk path, etc) 81 | 82 | # Proguard folder generated by Eclipse 83 | 84 | # Log Files 85 | 86 | # Android Studio 87 | /*/build/ 88 | /*/local.properties 89 | /*/out 90 | /*/*/build 91 | /*/*/production 92 | *.ipr 93 | *~ 94 | *.swp 95 | 96 | # Android Patch 97 | 98 | # External native build folder generated in Android Studio 2.2 and later 99 | 100 | # NDK 101 | obj/ 102 | 103 | # IntelliJ IDEA 104 | *.iws 105 | /out/ 106 | 107 | # User-specific configurations 108 | .idea/libraries/ 109 | .idea/.name 110 | .idea/compiler.xml 111 | .idea/copyright/profiles_settings.xml 112 | .idea/encodings.xml 113 | .idea/misc.xml 114 | .idea/modules.xml 115 | .idea/scopes/scope_settings.xml 116 | .idea/vcs.xml 117 | .idea/jsLibraryMappings.xml 118 | .idea/datasources.xml 119 | .idea/dataSources.ids 120 | .idea/sqlDataSources.xml 121 | .idea/dynamic.xml 122 | .idea/uiDesigner.xml 123 | 124 | # Keystore files 125 | 126 | # OS-specific files 127 | .DS_Store 128 | .DS_Store? 129 | ._* 130 | .Spotlight-V100 131 | .Trashes 132 | ehthumbs.db 133 | Thumbs.db 134 | 135 | # Legacy Eclipse project files 136 | .classpath 137 | .project 138 | 139 | # Mobile Tools for Java (J2ME) 140 | .mtj.tmp/ 141 | 142 | # Package Files # 143 | *.jar 144 | *.war 145 | *.ear 146 | 147 | # virtual machine crash logs (Reference: http://www.java.com/en/download/help/error_hotspot.xml) 148 | hs_err_pid* 149 | 150 | ## Plugin-specific files: 151 | 152 | # mpeltonen/sbt-idea plugin 153 | .idea_modules/ 154 | 155 | # JIRA plugin 156 | atlassian-ide-plugin.xml 157 | 158 | # Mongo Explorer plugin 159 | .idea/mongoSettings.xml 160 | 161 | # Crashlytics plugin (for Android Studio and IntelliJ) 162 | com_crashlytics_export_strings.xml 163 | crashlytics.properties 164 | crashlytics-build.properties 165 | fabric.properties 166 | 167 | ### AndroidStudio Patch ### 168 | # Google Services plugin 169 | 170 | !/gradle/wrapper/gradle-wrapper.jar 171 | 172 | ### Java ### 173 | # Compiled class file 174 | 175 | # Log file 176 | 177 | # BlueJ files 178 | *.ctxt 179 | 180 | # Mobile Tools for Java (J2ME) 181 | 182 | # Package Files # 183 | *.zip 184 | *.tar.gz 185 | *.rar 186 | 187 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 188 | 189 | ### Linux ### 190 | 191 | # temporary files which can be created if a process still has a handle open of a deleted file 192 | .fuse_hidden* 193 | 194 | # KDE directory preferences 195 | .directory 196 | 197 | # Linux trash folder which might appear on any partition or disk 198 | .Trash-* 199 | 200 | # .nfs files are created when an open file is removed but is still being accessed 201 | .nfs* 202 | 203 | ### macOS ### 204 | *.DS_Store 205 | .AppleDouble 206 | .LSOverride 207 | 208 | # Icon must end with two \r 209 | Icon 210 | 211 | # Thumbnails 212 | 213 | # Files that might appear in the root of a volume 214 | .DocumentRevisions-V100 215 | .fseventsd 216 | .TemporaryItems 217 | .VolumeIcon.icns 218 | .com.apple.timemachine.donotpresent 219 | 220 | # Directories potentially created on remote AFP share 221 | .AppleDB 222 | .AppleDesktop 223 | Network Trash Folder 224 | Temporary Items 225 | .apdisk 226 | 227 | ### Windows ### 228 | # Windows thumbnail cache files 229 | ehthumbs_vista.db 230 | 231 | # Folder config file 232 | Desktop.ini 233 | 234 | # Recycle Bin used on file shares 235 | $RECYCLE.BIN/ 236 | 237 | # Windows Installer files 238 | *.cab 239 | *.msi 240 | *.msm 241 | *.msp 242 | 243 | # Windows shortcuts 244 | *.lnk 245 | 246 | ### Gradle ### 247 | /build/ 248 | 249 | # Ignore Gradle GUI config 250 | gradle-app.setting 251 | 252 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 253 | !gradle-wrapper.jar 254 | 255 | # Cache of project 256 | .gradletasknamecache 257 | 258 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 259 | # gradle/wrapper/gradle-wrapper.properties 260 | 261 | # End of https://www.gitignore.io/api/java,macos,linux,gradle,windows,android,androidstudio 262 | -------------------------------------------------------------------------------- /code-files/mavencentral_push.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2013 Chris Banes 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | apply plugin: 'maven' 18 | apply plugin: 'signing' 19 | 20 | def isReleaseBuild() { 21 | return VERSION_NAME.contains("SNAPSHOT") == false 22 | } 23 | 24 | def getReleaseRepositoryUrl() { 25 | return hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL : 26 | "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 27 | } 28 | 29 | def getSnapshotRepositoryUrl() { 30 | return hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL : 31 | "https://oss.sonatype.org/content/repositories/snapshots/" 32 | } 33 | 34 | def getRepositoryUsername() { 35 | return hasProperty('NEXUS_USERNAME') ? NEXUS_USERNAME : "" 36 | } 37 | 38 | def getRepositoryPassword() { 39 | return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" 40 | } 41 | 42 | afterEvaluate { project -> 43 | uploadArchives { 44 | repositories { 45 | mavenDeployer { 46 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 47 | 48 | pom.groupId = GROUP 49 | pom.artifactId = POM_ARTIFACT_ID 50 | pom.version = VERSION_NAME 51 | 52 | repository(url: getReleaseRepositoryUrl()) { 53 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 54 | } 55 | snapshotRepository(url: getSnapshotRepositoryUrl()) { 56 | authentication(userName: getRepositoryUsername(), password: getRepositoryPassword()) 57 | } 58 | 59 | pom.project { 60 | name POM_NAME 61 | packaging POM_PACKAGING 62 | description POM_DESCRIPTION 63 | url POM_URL 64 | 65 | scm { 66 | url POM_SCM_URL 67 | connection POM_SCM_CONNECTION 68 | developerConnection POM_SCM_DEV_CONNECTION 69 | } 70 | 71 | licenses { 72 | license { 73 | name POM_LICENCE_NAME 74 | url POM_LICENCE_URL 75 | distribution POM_LICENCE_DIST 76 | } 77 | } 78 | 79 | developers { 80 | developer { 81 | id POM_DEVELOPER_ID 82 | name POM_DEVELOPER_NAME 83 | } 84 | } 85 | } 86 | } 87 | } 88 | } 89 | 90 | signing { 91 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 92 | sign configurations.archives 93 | } 94 | 95 | //task androidJavadocs(type: Javadoc) { 96 | //source = android.sourceSets.main.allJava 97 | //} 98 | 99 | //task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) { 100 | //classifier = 'javadoc' 101 | //from androidJavadocs.destinationDir 102 | //} 103 | 104 | task androidSourcesJar(type: Jar) { 105 | classifier = 'sources' 106 | from android.sourceSets.main.java.sourceFiles 107 | } 108 | 109 | artifacts { 110 | archives androidSourcesJar 111 | } 112 | } -------------------------------------------------------------------------------- /deploy-to-github-pages.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "" 4 | echo "Deploying to github pages..." 5 | echo "" 6 | 7 | # Cleanup up last rendered book 8 | mdbook clean 9 | 10 | # Build the book from src dir 11 | mdbook build 12 | 13 | # Checkout to gh-pages dir 14 | git checkout gh-pages 15 | 16 | # Delete existing docs dir 17 | rm -rf docs 18 | 19 | # Rename book dir to docs 20 | mv book docs 21 | 22 | # Add to git 23 | git add . 24 | 25 | # Commit 26 | git commit -m "updated book with latest changes" 27 | 28 | # Push to deploy 29 | git push origin gh-pages 30 | 31 | # Switch back to last branch 32 | git checkout - 33 | -------------------------------------------------------------------------------- /src/SUMMARY.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | - [Introduction](./introduction.md) 4 | - [Mastering Android Studio]() 5 | - [Code faster by using keyboard shortcuts](./code-faster-using-keyboard.md) 6 | - [Use plugins to become more efficient](./use-plugins-in-as.md) 7 | - [Speed code using code-completion](./use-code-completion-in-as.md) 8 | - [Configuring Android Studio](./configure-as.md) 9 | - [Playing in the Terminal]() 10 | - [Get used to ADB Shell](./adb-shell.md) 11 | - [Setup Android Aliases](./android-aliases.md) 12 | - [scrcpy: Control/Share your Android device](./scrcpy.md) 13 | - [Gradle FTW]() 14 | - [Working with Gradle Wrapper](./working-with-gradle-wrapper.md) 15 | - [Gradle: Groovy Script Tricks](./gradle-groovy-script-tips.md) 16 | - [Gradle: Kotlin Script Tricks](./gradle-kotlin-script-tips.md) 17 | - [Make better choices while coding](./make-better-choices-while-coding.md) 18 | - [Tips regarding UI/UX](./tips-regarding-uiux.md) 19 | - [Tips if you use Kotlin](./tips-if-you-use-kotlin.md) 20 | - [Misc Tips](./misc.md) 21 | - [Embrace the community]() 22 | - [Podcasts to listen](./podcasts.md) 23 | - [Learning Resources](./learning-resources.md) 24 | - [Examples to learn from](./android-examples.md) 25 | - [Make use of Helper tools](./helper-tools.md) 26 | -------------------------------------------------------------------------------- /src/adb-shell.md: -------------------------------------------------------------------------------- 1 | # ADB Shell 2 | 3 | Few handy commands you can use to interact with emulator/device, through terminal. 4 | 5 | | Description | Command | 6 | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- | 7 | | List all connected devices | `adb devices` | 8 | | Install an application on device
-s to install on the SD Card
-g to grant all permissions listed in the manifest [[More Info]](https://developer.android.com/studio/command-line/adb.html) | `adb install -r ~/application.apk` | 9 | | Uninstall an application | `adb uninstall your.app.package` | 10 | | Download a file from device | `adb pull /sdcard/file.ext` | 11 | | Upload a file to a device | `adb push file.ext /sdcard` | 12 | | Print all installed packages on device | `adb shell pm list packages -f` | 13 | | Clear Application data | `adb shell pm clear your.app.package` | 14 | | Toggle Data for device | `adb shell svc data disable` | 15 | | Toggle Wifi for device | `adb shell svc wifi enable` | 16 | | Location of Device
- High accuracy: gps,wifi,network or gps,network (if you want the wifi)
- Battery saving: wifi,network or network only
- Device only: gps | `adb shell settings put secure location_providers_allowed gps` | 17 | | Reset all granted permissions | `adb shell pm reset-permissions -p your.app.package` | 18 | | Reset a specific permission | `adb shell pm revoke your.app.package android.permission.WRITE_EXTERNAL_STORAGE` | 19 | | Broadcast Actions | `adb shell am broadcast -a 'my_action'` | 20 | | [Simulating Android killing your app in the background](https://twitter.com/Jahnold/status/759775495655333888) | `adb shell am kill` | 21 | | Take a Screenshot | `adb shell screencap -p \| perl -pe 's/\x0D\x0A/\x0A/g' > screenshot.png` | 22 | | Launch an installed app using its package name | `adb shell monkey -p com.yourapp.packagename 1` | 23 | | [Stress test](https://developer.android.com/studio/test/monkey) your app using its package name by sending a pseudo-random stream of user events into the system | `adb shell monkey -p com.yourapp.packagename -v 500` | 24 | | Send input text to a connected device instead of typing manually. | `adb shell input text "helloworld@xyz.com"` | 25 | | Check device logs | `adb logcat` | 26 | | To save Android device logs locally on your computer using ADB | `adb logcat > device_logs.txt` | 27 | 28 | 29 | - **[Learn about various techniques involved when using ADB](https://crushingcode.nisrulz.com/posts/do-you-like-to-adb/)** 30 | -------------------------------------------------------------------------------- /src/android-aliases.md: -------------------------------------------------------------------------------- 1 | # Setup Android Aliases 2 | 3 | Append the below **Aliases** to your `~/.bashrc` or `~/.zshrc` file, save and restart the terminal. Once saved, use them as show in **Usage** column 4 | 5 | ```bash 6 | ############################################################# 7 | # Setup Android Paths 8 | ############################################################# 9 | 10 | # Path to Android SDK (This is for Mac, replace for your OS) 11 | export ANDROID_HOME=$HOME/Library/Android/sdk 12 | 13 | # Path to NDK 14 | export ANDROID_NDK_HOME=$ANDROID_HOME/ndk/22.1.7171670 15 | 16 | # Path to Android platform tools (adb, fastboot, etc) 17 | export ANDROID_PLATFORM_TOOLS="$ANDROID_HOME/platform-tools" 18 | 19 | # Path to Android tools (monitor, mksdcard, emulator-check, emulator, etc) 20 | export ANDROID_TOOLS_1="$ANDROID_HOME/tools" 21 | 22 | # Path to Android tools (apkanalyzer, avdmanager, monkeyrunner, lint, sdkmanager etc) 23 | export ANDROID_TOOLS_2="$ANDROID_HOME/tools/bin" 24 | 25 | # Path to Android tools (aapt, apksigner, zipalign, etc) 26 | export ANDROID_TOOLS_3="$ANDROID_HOME/build-tools/29.0.3/" 27 | 28 | # Path to Android tools (emulator) 29 | export ANDROID_TOOLS_4="$ANDROID_HOME/emulator/" 30 | 31 | # Add all to the path 32 | export PATH="$PATH:$ANDROID_PLATFORM_TOOLS:$ANDROID_TOOLS:$ANDROID_TOOLS_2:$ANDROID_TOOLS_3:$ANDROID_TOOLS_4" 33 | 34 | ############################################################# 35 | # Setup Android Aliases 36 | ############################################################# 37 | 38 | # Do an incremental install of APK 39 | # Usage: incrementalInstall 40 | alias incrementalInstall="adb intall --fastdeploy" 41 | 42 | # Alias to run local test while only showing failed tests as output 43 | # Usage: runLocalTest 44 | alias runLocalTest="./gradlew --rerun-tasks test | grep FAILED" 45 | 46 | # Delete all build folders in an Android project 47 | # Usage: deleteAllBuildDirs 48 | alias deleteAllBuildDirs='find . -type d -name "build" \ 49 | | while read f; do echo "🔥Deleting: $f" && rm -rf "$f"; done' 50 | 51 | # Install and Grant all permissions for an apk 52 | # Usage: grantAllPermissionsForApk path/to/apk/Application.apk 53 | alias grantAllPermissionsForApk="adb install -g $1" 54 | 55 | # Take a screenshot 56 | # Usage: screenshot 57 | alias screenshot="adb exec-out screencap -p > screen-$(date -j "+%s").png" 58 | 59 | # Fire an intent 60 | # Usage: startIntent https://twitter.com/nisrulz 61 | alias startIntent="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X shell am start $1" 62 | 63 | # Install Apk 64 | # Note: As an alternative to apkInstall, you can also do just ./gradlew installDebug 65 | # Usage: apkInstall ~/path/to/apk/App.apk 66 | alias apkInstall="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X install -r $1" 67 | 68 | # Uninstall an app 69 | # Usage: rmApp com.example.demoapp 70 | alias rmApp="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X uninstall $1" 71 | 72 | # Clear all data of an app 73 | # Usage: clearApp com.example.demoapp 74 | alias clearApp="adb devices | tail -n +2 | cut -sf 1 | xargs -I X adb -s X shell pm clear $1" 75 | 76 | # Get package name of the passed apk file 77 | # Usage: getPackageName app-debug.apk 78 | alias getPackageName="apkanalyzer -h manifest application-id $1" 79 | 80 | # Alias for building and installing the apk to connected device 81 | # Use as: buildAndInstallApk path/to/apk_file.apk 82 | # Example: To build and install debug apk 83 | # > buildAndInstallApk ./app/build/outputs/apk/debug/app-debug.apk 84 | alias buildAndInstallApk="./gradlew assembleDebug && apkinstall $1" 85 | 86 | # Launch your apk on your connected device 87 | # Execute at the root of your android project 88 | # Usage: launchApk path/to/apk_file.apk 89 | # Example: To launch debug apk 90 | # > launchApk ./app/build/outputs/apk/debug/app-debug.apk 91 | alias launchApk="adb shell monkey -p $(getPackageName $1) 1" 92 | 93 | # Single command to build+install+launch apk 94 | # Execute at the root of your android project 95 | # Use as: buildInstallLaunchApk path/to/apk_file.apk 96 | # Example: To build, install and launch debug apk 97 | # > buildInstallLaunchApk ./app/build/outputs/apk/debug/app-debug.apk 98 | alias buildInstallLaunchApk="buildAndInstallApk $1 && launchDebugApk $1" 99 | 100 | # ------------- Demo Mode ------------# 101 | 102 | # Demo Mode : https://android.googlesource.com/platform/frameworks/base/+/master/packages/SystemUI/docs/demo_mode.md 103 | 104 | # Enable Demo Mode on your device 105 | # Usage: enableDemoMode 106 | alias enableDemoMode="adb shell settings put global sysui_demo_allowed 1 \ 107 | && adb shell am broadcast \ 108 | -a com.android.systemui.demo -e command clock -e hhmm 1200 \ 109 | && adb shell am broadcast \ 110 | -a com.android.systemui.demo -e command network \ 111 | -e mobile show -e level 4 -e datatype false \ 112 | && adb shell am broadcast -a com.android.systemui.demo \ 113 | -e command notifications \ 114 | -e visible false && adb shell am broadcast \ 115 | -a com.android.systemui.demo -e command battery \ 116 | -e plugged false -e level 100" 117 | 118 | # Disable Demo Mode on your device 119 | # Usage: disableDemoMode 120 | alias disableDemoMode="adb shell am broadcast -a com.android.systemui.demo -e command exit" 121 | 122 | # ------------- Dev Mode:Layout Bounds ------------# 123 | 124 | # Ref link: https://ivanmorgillo.com/2021/06/24/show-layout-bounds-from-command-line/ 125 | # Enable Layout Bounds developer options 126 | # Usage: devLayoutBoundsOn 127 | alias devLayoutBoundsOn='adb shell setprop debug.layout true; adb shell service call activity 1599295570 > /dev/null' 128 | 129 | # Disable Layout Bounds developer options 130 | # Usage: devLayoutBoundsOff 131 | alias devLayoutBoundsOff='adb shell setprop debug.layout false ; adb shell service call activity 1599295570 > /dev/null' 132 | 133 | ############################################################# 134 | # Setup Android Bash Functions 135 | ############################################################# 136 | 137 | # Uninstall all installed apps from the connected device 138 | # whose package name matches the passed pattern 139 | # Usage: uninstallAppsMatchingPackagePattern github.nisrulz. 140 | function uninstallAppsMatchingPackagePattern(){ 141 | echo "" 142 | # Break down of the long command 143 | # adb shell 'pm list packages -u' = Get all packages 144 | # grep github.nisrulz = Filter out the packages that contain value of $1 arg 145 | # cut -c 9- = Remove the first 9 chars, which correspond to package: 146 | # rev = Reverse the string 147 | # cut -c 2- = Remove the first 2 chars, which correspond to ^M 148 | # rev = Reverse the string 149 | for pkg in $(adb shell 'pm list packages -u' | grep $1 | cut -c 9- | rev | cut -c 2- | rev); do 150 | echo "-- Removing $pkg" 151 | adb uninstall $pkg 152 | done 153 | } 154 | 155 | # Usage: Navigate to the library directory and execute the below 156 | # > ndk_stack_tracing 157 | function ndk_stack_tracing(){ 158 | adb logcat | $ANDROID_NDK_HOME/ndk-stack -sym ./build/intermediates/library_jni/debug/jni/arm64-v8a/ 159 | } 160 | 161 | # Stress test the debug apk with 100000 ui events 162 | # Execute at the root of your android project 163 | # Use as: stressTestApk apk_file.apk 164 | function stressTestApk() { 165 | local APP_PACKAGE_NAME=$(getPackageName $1) 166 | adb shell monkey -p $APP_PACKAGE_NAME 100000 167 | } 168 | 169 | # Find the usage of OptIn annotation in codebase 170 | # Usage: findOptInAnnotationUsage 171 | function findOptInAnnotationUsage(){ 172 | grep -r -F "@OptIn(" ./ 173 | } 174 | 175 | # ADB Over Wifi 176 | # Usage: adbOverWifi 177 | function adbOverWifi() { 178 | local DEVICE_ID=$(adb devices | awk 'NR==2{print $1; exit}') 179 | echo "Device ID: $DEVICE_ID" 180 | 181 | local LOCAL_WIFI_IP=$(adb shell ip route | awk 'NR==1{print $9}') 182 | echo "Local Wifi IP: $LOCAL_WIFI_IP" 183 | 184 | local PORT=5555 185 | adb tcpip $PORT 186 | adb connect $LOCAL_WIFI_IP:$PORT 187 | sleep 1 188 | adb devices 189 | } 190 | ``` 191 | -------------------------------------------------------------------------------- /src/android-examples.md: -------------------------------------------------------------------------------- 1 | # Examples to learn from 2 | 3 | - [Android Examples](https://github.com/nisrulz/android-examples) - Simple basic isolated apps, for budding android devs. 4 | - [Google Samples](https://github.com/googlesamples) - Various sample apps provided by Google 5 | - [Google Android Codelabs](https://codelabs.developers.google.com/?cat=Android) 6 | - [Google Android Codelabs](https://codelabs.developers.google.com/?cat=Android) 7 | - [QualityMatters](https://github.com/artem-zinnatullin/qualitymatters) 8 | - [Android-Testing](https://github.com/googlesamples/android-testing) 9 | - [Espresso-Samples](https://github.com/chiuki/espresso-samples) 10 | -------------------------------------------------------------------------------- /src/code-faster-using-keyboard.md: -------------------------------------------------------------------------------- 1 | # Code faster by using keyboard shortcuts 2 | 3 | | Description | Mac | Linux/Win | 4 | |-----------------------------------------------------------------------------------|----------------------------------------------------------------|-----------------------------------------------------------------------------| 5 | | Lookup IDE commands / Actions | Cmd Shift A | Ctrl Shift A | 6 | | Open Class | Cmd O | Ctrl O | 7 | | Open File | Cmd Shift O | Ctrl Shift N | 8 | | Open recently edited file | Cmd Shift E | Ctrl Shift E | 9 | | Open Symbol | Cmd Opt O | Alt Shift N | 10 | | Open recently used file | Cmd E | Ctrl E | 11 | | Last Edited Location | Cmd Shift Backspace | Ctrl Shift Backspace | 12 | | Find Usage in persistent window | Opt F7 | Alt F7 | 13 | | Find Usage in floating window | Cmd Opt F7 | Ctrl Alt F7 | 14 | | Format the code with proper Indentation | Cmd Opt L | Ctrl Alt L | 15 | | Surround With | Opt Cmd T | Alt Ctrl T | 16 | | Open Terminal | Opt F12 | Alt F12 | 17 | | Generate Setter/Getters | Cmd N | Alt Ins | 18 | | Find Class | CMD O | Ctrl N | 19 | | Refactor/Rename | Shift F6 | Shift F6 | 20 | | Quick Fix | Opt Enter | Alt Enter | 21 | | Goto Definition | Cmd B | Ctrl B | 22 | | Show parameters for selected method | Cmd P | Ctrl P | 23 | | Refactor This | Ctrl T | Ctrl Alt Shift T | 24 | | Stop Process | Cmd F2 | Ctrl F2 | 25 | | Search Everywhere | Shift Shift | Shift Shift | 26 | | Select Methods to Override | Ctrl O | Ctrl O | 27 | | Delete Line | Cmd Backspace | Ctrl Y | 28 | | Duplicate Line | Cmd D | Ctrl D | 29 | | Grow/Shrink selection from cursor | Opt Up/Down Arrow key | Shift Ctrl W | 30 | | [Multicursor Selection](https://android.jlelse.eu/ctrl-g-d94c88cd4475#.55flqgkb3) | Ctrl G | Alt J | 31 | 32 | 33 | **Complete Keymap Guide : [Linux/Win | MacOSX](https://resources.jetbrains.com/storage/products/intellij-idea/docs/IntelliJIDEA_ReferenceCard.pdf)** 34 | 35 | ### Other Tips/Tricks 36 | 37 | - Did you know you can quickly lookup the definition of any function by navigating to the function call and using `Opt + Space` on macOS or `Alt + Space` on Win/Linux inside Android Studio🙀 [[Ref Tweet](https://twitter.com/nisrulz/status/1291115617651699712)] 38 | 39 | ![quicklookup_def](img/quicklookup_def.gif) 40 | 41 | - Annoyed by the Design view always opening up when you open a layout or drawable xml file?🙄Navigate to Preferences ▶️Editor ▶️Layout Editor and choose "Code" option, to always open in Code view. [[Ref Tweet](https://twitter.com/nisrulz/status/12908175832565678084)] 42 | 43 | ![always_use_code_view](img/always_use_code_view.png) 44 | 45 | - If you want to use keyboard shortcuts with bookmarks, then make use of "Bookmark with Mnemonic". Once assigned a number, you can jump to the bookmark using `Ctrl + Number`. [[Ref Tweet](https://twitter.com/nisrulz/status/1293643013877637120)] 46 | 47 | ![bookmarks_mnemonic_as](img/bookmarks_mnemonic_as.gif) 48 | 49 | - When working with a class file dat has a lot of loc, often times one needs to jump between some parts of the same file. To do that, one can use the "Bookmarks" in Android Studio! Simply mark the line of code as Bookmark & open up the Bookmark Panel to jump. [[Ref Tweet](https://twitter.com/nisrulz/status/1293642003792748548)] 50 | 51 | ![bookmarks_as](img/bookmarks_as.gif) 52 | 53 | - Bunch of quick tips about refactoring under this [blogpost I wrote for raywenderlich.com](https://www.raywenderlich.com/2807578-android-studio-tips-and-tricks) 54 | -------------------------------------------------------------------------------- /src/configure-as.md: -------------------------------------------------------------------------------- 1 | # Configuring Android Studio 2 | 3 | ## Use the Darcula Theme in Android Studio 4 | 5 | Ok, I know its more like a preference, but trust me using that keeps your eyes less strained as they would be if you used the Default Light theme. 6 | 7 | ## Don't use a small font 8 | 9 | Preferably use a font in Android Studio that's easy to read and is at a font size which does not forces you to strain your eyes. Also using fonts that support lingature increases readeablity. While everyone has a preferred font, below are some options for interested folks: 10 | 11 | - [Jetbrains Mono](https://www.jetbrains.com/lp/mono/) 12 | - [FiraCode](https://github.com/tonsky/FiraCode) 13 | 14 | ## Use a code style 15 | 16 | You should use a standard codestyle, so possible contenders can be 17 | 18 | - [AOSP Codestyle](https://source.android.com/source/code-style.html) 19 | - [Square IntelliJ Codestyle](https://github.com/square/java-code-styles) 20 | - [Grandcentrix Codestyle](https://github.com/grandcentrix/AndroidCodeStyle) 21 | 22 | ## Misc tips 23 | 24 | * **Use the [Embedded Terminal inside Android Studio](https://www.jetbrains.com/help/idea/2016.2/working-with-embedded-local-terminal.html)** 25 | 26 | * **Use the Memory/Network/CPU Monitor inside Android Studio to profile your code/app** 27 | 28 | * **[Configure Android Studio for speed](https://medium.com/google-developer-experts/configuring-android-studio-4aa4f54f1153#.rq0z6qlaq)** -------------------------------------------------------------------------------- /src/extra-android-libraries-built-by-me.md: -------------------------------------------------------------------------------- 1 | # Extra : Android Libraries built by me 2 | 3 | - [EasyDeviceInfo](https://github.com/nisrulz/easydeviceinfo) - Enabling device information to be at android developers hand like a piece of cake! 4 | - [Sensey](https://github.com/nisrulz/Sensey) - Android library to make detecting gestures easy 5 | - [ValidateTor](https://github.com/nisrulz/validatetor) - Android library for fast and simple string validation. 6 | - [PackageHunter](https://github.com/nisrulz/PackageHunter) - Android library to hunt down package information 7 | - [Zentone](https://github.com/nisrulz/zentone) - Easily generate audio tone in android 8 | - [RecyclerViewHelper](https://github.com/nisrulz/recyclerviewhelper) - RecyclerViewHelper provides the most common functions around recycler view like Swipe to dismiss, Drag and Drop, Divider in the ui, events for when item selected and when not selected, on-click listener for items. 9 | - [android-utils](https://github.com/nisrulz/android-utils) - Android Library facilitating some very common functionalities in the form of utility classes for Android. 10 | - [Lantern](https://github.com/nisrulz/lantern) - Android library handling flashlight for camera and camera2 api. Added support for handling display/screen light. 11 | - [StackedHorizontalProgressbar](https://github.com/nisrulz/stackedhorizontalprogressbar) - Android Library to implement stacked horizontal progressbar 12 | - [QREader](https://github.com/nisrulz/qreader) - A library that uses google's mobile vision api and simplifies the QR code reading process 13 | - [ScreenShott](https://github.com/nisrulz/screenshott) - Simple library to take a screenshot of the device screen, programmatically! 14 | - [EvTrack](https://github.com/nisrulz/EvTrack) - Android library to make event and exception tracking easy 15 | - [OptimusHTTP](https://github.com/nisrulz/OptimusHTTP) - Android library that simplifies networking in android via an async http client 16 | -------------------------------------------------------------------------------- /src/gradle-groovy-script-tips.md: -------------------------------------------------------------------------------- 1 | # Gradle: Groovy Script Tricks 2 | 3 | * **Use proguard** 4 | 5 | ```groovy 6 | android { 7 | ... 8 | buildTypes { 9 | release { 10 | minifyEnabled true 11 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 12 | } 13 | } 14 | } 15 | ``` 16 | 17 | [[Read more from the manual here](https://www.guardsquare.com/en/proguard/manual/usage)] 18 | 19 | * **Use shrinkResources** 20 | 21 | ```groovy 22 | android { 23 | ... 24 | buildTypes { 25 | release { 26 | shrinkResources true 27 | minifyEnabled true 28 | ... 29 | } 30 | } 31 | } 32 | ``` 33 | 34 | * **Split your apk using gradle when using Native code, do not bundle all of em together and ship!.. coz that will make you evil** 35 | 36 | ```groovy 37 | defaultConfig { 38 | ... 39 | 40 | ndk { 41 | abiFilters "armeabi", "armeabi-v7a", "mips", "x86" 42 | } 43 | } 44 | 45 | //Split into platform dependent APK 46 | splits { 47 | abi { 48 | enable true 49 | reset() 50 | include 'armeabi', 'armeabi-v7a', 'mips', 'x86' //select ABIs to build APKs for 51 | universalApk false //generate an additional APK that contains all the ABIs 52 | } 53 | } 54 | 55 | // map for the version code 56 | project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'mips': 5, 'x86': 8] 57 | 58 | // Rename with proper versioning 59 | android.applicationVariants.all { variant -> 60 | // assign different version code for each output 61 | variant.outputs.each { output -> 62 | output.versionCodeOverride = 63 | project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 64 | 1000000 + 65 | android.defaultConfig.versionCode 66 | } 67 | } 68 | ``` 69 | 70 | * **To have the each subproject script name match that of the project name** 71 | 72 | Then add this line in settings.gradle 73 | 74 | ```groovy 75 | rootProject.children.each{ 76 | it.buildFileName = it.name + '.gradle' 77 | } 78 | ``` 79 | 80 | * **Use different package name for non-release builds** 81 | 82 | ```groovy 83 | android { 84 | buildTypes { 85 | debug { 86 | applicationIdSuffix '.debug' 87 | versionNameSuffix '-DEBUG' 88 | } 89 | 90 | release { 91 | // ... 92 | } 93 | } 94 | } 95 | ``` 96 | 97 | * **Setup Android Studio to fail build if code contains `//STOPSHIP`** [[Ref Link]](https://www.reddit.com/r/androiddev/comments/5c8b0a/i_know_android_studio_allows_you_to_make_custom/d9uhdzt/) 98 | 99 | To enable the `//STOPSHIP` lint check, in your `build.gradle` 100 | 101 | ```groovy 102 | android { 103 | ... 104 | lintOptions { 105 | abortOnError true 106 | fatal 'StopShip' 107 | } 108 | } 109 | ``` 110 | 111 | If you have a `//STOPSHIP` comment in your code, this will cause an error to be thrown when a release apk is generated. 112 | 113 | > You can turn on //STOPSHIP highlighting in Android Studio (isn't enabled by default) in 114 | > 115 | > `Preferences` > `Editor` > `Code Style` > `Inspections`. 116 | > 117 | > Search for STOPSHIP to find the correct setting. 118 | 119 | * **Output unit tests directly to the console** [[Ref Link]](https://medium.com/@cesarmcferreira/mastering-the-terminal-side-of-android-development-e7520466c521#.1cw4bto7f) 120 | 121 | > A small neat trick to see Android unit tests logging results as they happen in the terminal. 122 | 123 | ```groovy 124 | android { 125 | ... 126 | testOptions.unitTests.all { 127 | testLogging { 128 | events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' 129 | outputs.upToDateWhen { false } 130 | showStandardStreams = true 131 | } 132 | } 133 | } 134 | ``` 135 | 136 | * **Define a variable at build time** 137 | In your `build.gradle` 138 | 139 | ```groovy 140 | android{ 141 | defaultConfig { 142 | ... 143 | buildConfigField "String", "SERVER_ENDPOINT", '"http://www.myendpoint.com"' 144 | buildConfigField "int", "FOO", "52" 145 | buildConfigField "boolean", "LOG", "false" 146 | ... 147 | } 148 | } 149 | ``` 150 | 151 | and then use it in code as `BuildConfig.SERVER_ENDPOINT`, `BuildConfig.FOO`,`BuildConfig.LOG` 152 | 153 | * **Calculate the version code and version name in your `build.gradle` **manually**_, based of version values_** 154 | In your app's `build.gradle` 155 | 156 | ```groovy 157 | versionMajor = 0 158 | versionMinor = 0 159 | versionPatch = 0 160 | versionBuild = 1 161 | 162 | verCode = versionMajor _ 1000000 + versionMinor _ 10000 + versionPatch \* 100 + versionBuild 163 | verName = "${versionMajor}.${versionMinor}.${versionPatch}" 164 | 165 | // Use 166 | android{ 167 | defaultConfig { 168 | ... 169 | versionCode verCode 170 | versionName verName 171 | ... 172 | } 173 | } 174 | ``` 175 | 176 | - **Calculate the version code and version name in your `build.gradle` automatically, based on git information** 177 | 178 | > Note: These functions go specifically inside the app's `build.gradle` and cannot be used with `ext`. 179 | 180 | In your app's `build.gradle` 181 | 182 | ```groovy 183 | // Version code is calculated as the number of commits from last commit on master 184 | def getVersionCode = { -> 185 | try { 186 | def code = new ByteArrayOutputStream() 187 | exec { 188 | commandLine 'git', 'rev-list', 'HEAD', '--count' 189 | standardOutput = code 190 | } 191 | return Integer.parseInt(code.toString().trim()) 192 | } catch (exception) { 193 | return "1"; 194 | } 195 | } 196 | 197 | // Version name is Last Tag Name + No. of commits form last Tag + short git sha 198 | def getVersionName = { -> 199 | try { 200 | def stdout = new ByteArrayOutputStream() 201 | exec { 202 | commandLine 'git', 'describe', '--tags', '--dirty' 203 | standardOutput = stdout 204 | } 205 | return stdout.toString().trim() 206 | } catch (exception) { 207 | return "0.0.0.1"; 208 | } 209 | } 210 | 211 | // Use 212 | android{ 213 | defaultConfig { 214 | ... 215 | versionCode getVersionCode() 216 | versionName getVersionName() 217 | ... 218 | } 219 | } 220 | ``` 221 | 222 | * **Get the date of build as a variable** 223 | In your app's `build.gradle` 224 | 225 | ```groovy 226 | // Get the date of build 227 | def getDateOfBuild = { -> // ISO 8601 time format 228 | return new Date().format("yyyy-MM-dd'T'HH:mm'Z'").toString().trim() 229 | } 230 | 231 | // then use it as a variable in BuildConfig 232 | android{ 233 | defaultConfig { 234 | ... 235 | buildConfigField "String", "DATE_OF_BUILD", "\"${getDateOfBuild()}\"" 236 | } 237 | } 238 | ``` 239 | 240 | * **Get the Git SHA as a variable** 241 | In your app's `build.gradle` 242 | 243 | ```groovy 244 | // Get the last Git Short Hash 245 | def getGitHash = { -> 246 | def stdout = new ByteArrayOutputStream() 247 | exec { 248 | commandLine 'git', 'rev-parse', '--short', 'HEAD' 249 | standardOutput = stdout 250 | } 251 | return stdout.toString().trim() 252 | } 253 | 254 | // then use it as a variable in BuildConfig 255 | android{ 256 | defaultConfig { 257 | ... 258 | buildConfigField "String", "GIT_SHA", "\"${getGitHash()}\"" 259 | } 260 | } 261 | ``` 262 | 263 | > Have a look at the [Paperwork Project](https://github.com/zsoltk/paperwork), which generates build info for your Android project without breaking incremental compilation 264 | 265 | * **[Use Java 8 features by adding `sourceCompatibility` & `targetCompatibility` to your build.gradle file](https://developer.android.com/studio/preview/features/java8-support.html)** 266 | 267 | ```groovy 268 | android { 269 | ... 270 | compileOptions { 271 | sourceCompatibility JavaVersion.VERSION_1_8 272 | targetCompatibility JavaVersion.VERSION_1_8 273 | } 274 | } 275 | ``` 276 | 277 | * **[Setup a gradle task to archive apks and proguard files on build, for backup purposes](https://medium.com/pressure-labs/a-new-devs-guide-to-google-play-sanity-4-a-groovy-script-to-save-them-all-456a12672886)** 278 | 279 | ```groovy 280 | task deployApks(type:Copy) { 281 | description = "Copies APKs and Proguard mappings to the deploy directory" 282 | def appName = ""; 283 | def versionDir = android.defaultConfig.versionName+"_"+android.defaultConfig.versionCode; 284 | 285 | println("Copies APK and Proguard to " + versionDir) 286 | 287 | from 'build/outputs/mapping/release/' 288 | include '**/mapping.txt' 289 | into '../.admin/deploy/' + versionDir 290 | rename ('mapping.txt', "${versionDir}-mapping.txt") 291 | 292 | from ('.') { 293 | exclude '**/build', '**/src' 294 | } 295 | 296 | include '*.apk' 297 | into '../.admin/deploy/' + versionDir 298 | rename ('app-release.apk', "${appName}-${versionDir}.apk") 299 | } 300 | ``` 301 | 302 | * **Reference local `aar` files as below [[Stackoverflow Ref](http://stackoverflow.com/a/28816265/2745762)]** 303 | 304 | ```groovy 305 | dependencies { 306 | implementation(name:'nameOfYourAARFileWithoutExtension', ext:'aar') 307 | } 308 | repositories { 309 | flatDir { 310 | dirs 'libs' 311 | } 312 | } 313 | ``` 314 | 315 | * Get faster gradle builds by only using one resource configuration for your development builds [[Ref Link](https://developer.android.com/studio/build/optimize-your-build#reduce_resources)] 316 | 317 | ```groovy 318 | android { 319 | ... 320 | productFlavors { 321 | dev { 322 | ... 323 | // The following configuration limits the "dev" flavor to using 324 | // English stringresources and xxhdpi screen-density resources. 325 | resConfigs "en", "xxhdpi" 326 | } 327 | ... 328 | } 329 | } 330 | ``` 331 | 332 | * Specifying `buildToolsVersion` in your build.gradle files is optional when using Android plugin 3.0.0 or later. By default the plugin uses the minimum version of the build tools required by the version of the plugin you're using. [[Tweet Link](https://twitter.com/nisrulz/status/976730548084211718), [Ref Link](https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.LibraryExtension.html#com.android.build.gradle.LibraryExtension:buildToolsVersion)] 333 | 334 | ![dont_specify_buildtoolsversion](img/dont_specify_buildtoolsversion.jpg) 335 | 336 | * You can insert variables into AndroidManifest defined in `build.gradle` [[Tweet Link](https://twitter.com/jabbar_jigariyo/status/910754663925899264), [Ref Link](https://developer.android.com/studio/build/manifest-build-variables)] 337 | 338 | ![inject_vars_in_manifest](img/inject_vars_in_manifest.png) 339 | 340 | * **Make use of custom gradle tasks in your build.gradle files** 341 | 342 | Android uses Gradle as its build system, which actually allows one to make a lot of things easy by creating tasks to automate things. 343 | [This reddit post enlists a lot of such useful gradle scripts](https://www.reddit.com/r/androiddev/comments/3ig3gm/show_us_your_gradle_tasks) -------------------------------------------------------------------------------- /src/gradle-kotlin-script-tips.md: -------------------------------------------------------------------------------- 1 | # Gradle: Kotlin Script Tricks 2 | 3 | > Work in Progress -------------------------------------------------------------------------------- /src/helper-tools.md: -------------------------------------------------------------------------------- 1 | # Make use of Helper tools 2 | 3 | - [Android SVG to VectorDrawable](https://inloop.github.io/svg2android/) - One VectorDrawable to rule all screen densities 4 | - [SQLite Viewer](https://inloop.github.io/sqlite-viewer/) - View sqlite file online 5 | - [Android 9-patch shadow generator](https://inloop.github.io/shadow4android/) - Tool that makes fully customizable shadows possible 6 | - [APK method count](https://inloop.github.io/apk-method-count/) - Tool that outputs per-package method counts 7 | - [Material Palette](https://www.materialpalette.com/) - Easily generate the color pallete based on material design 8 | - [Color Tool](https://material.io/color/#!/) - Create, share and apply color palettes to your UI 9 | - [Javadoc Themer](https://javadoc-themer.firebaseapp.com/) - Give your boooring javadocs a splash of colors! 10 | - [Method Count](http://www.methodscount.com/) - Use this tool to avoid the dreaded 65K method limit of the DEX file format! 11 | - [Gradle, please](https://gradleplease.appspot.com/) - Lookup dependency reference name to include as your gradle dependencies 12 | - [jsonschema2pojo](http://www.jsonschema2pojo.org/) - Generate Plain Old Java Objects from JSON or JSON-Schema 13 | - [Android Asset Studio](http://romannurik.github.io/AndroidAssetStudio/) - A web-based set of tools for generating graphics and other assets that would eventually be in an Android application's res/ directory. 14 | - [Device Art Generator](https://developer.android.com/distribute/tools/promote/device-art.html) - Quickly wrap app screenshots in device artwork 15 | - [Google Translator Toolkit](https://translate.google.com/toolkit/list?hl=en#translations/) - Translate strings.xml files to any language and download as XML 16 | - [JSONViewer](http://jsonviewer.stack.hu/) - Awesome JSON formatter 17 | - [ExtendsClass](https://extendsclass.com/json-generator.html) - Random JSON Generator 18 | - [ShapeShifter](https://alexjlockwood.github.io/ShapeShifter/) - SVG path morphing animation editor. 19 | - [App Privacy Policy Generator](https://app-privacy-policy-generator.firebaseapp.com/) - Generate a generic privacy policy for your app for the playstore. 20 | - [gnirehtet](https://github.com/Genymobile/gnirehtet) - Reverse tethering for Android. 21 | - [Adaptive Icons](https://adapticon.tooo.io/) - Try out the new Adaptive Icons in your browser 22 | - [Android Starters](http://androidstarters.com/) - Handcrafted starter projects, optimized for simplicity and ease of use. 23 | - [Language Switcher Tile](https://github.com/AzimoLabs/Language-Switcher-Tile) - An android plugin that allows you to easily change your device language. 24 | - [Flipper](https://fbflipper.com/) - Flipper is a platform for debugging mobile apps on iOS and Android. Visualize, inspect, and control your apps from a simple desktop interface. 25 | 26 | - **Use freely available mockable api points** 27 | 28 | - [Mockey](https://github.com/clafonta/Mockey) - A tool for testing application interactions over http, with a focus on testing web services, specifically web applications that consume XML, JSON, and HTML. 29 | - [JSON Placeholder](http://jsonplaceholder.typicode.com/) - Fake Online REST API for Testing and Prototyping 30 | - [Mocky](http://www.mocky.io/) - Mock your HTTP responses to test your REST API 31 | - [Mockbin](http://mockbin.com) - Mockbin allows you to generate custom endpoints to test, mock, and track HTTP requests & responses between libraries, sockets and APIs. 32 | 33 | 34 | - **[ADB/Fastboot Tools made available as a separate package by google](https://plus.google.com/+ElliottHughes/posts/U3B6H3Sejvv), download latest version for** 35 | 36 | - [MacOSX](https://dl.google.com/android/repository/platform-tools-latest-darwin.zip) 37 | - [Linux](https://dl.google.com/android/repository/platform-tools-latest-linux.zip) 38 | - [Windows](https://dl.google.com/android/repository/platform-tools-latest-windows.zip) 39 | 40 | - **Awesome android libraries** 41 | - [StorIO](https://github.com/pushtorefresh/storio) - Beautiful API for SQLiteDatabase and ContentResolver 42 | - [Retrofit](https://github.com/square/retrofit) - Type-safe HTTP client for Android and Java by Square, Inc. 43 | - [Picasso](https://github.com/square/picasso) - A powerful image downloading and caching library for Android 44 | - [LeakCanary](https://github.com/square/leakcanary) - A memory leak detection library for Android and Java. 45 | - [AndroidViewAnimations](https://github.com/daimajia/AndroidViewAnimations) - Cute view animation collection. 46 | - [Calligraphy](https://github.com/chrisjenx/Calligraphy) - Custom fonts in Android the easy way. 47 | - [Alerter](https://github.com/Tapadoo/Alerter) - Android Alerting Library 48 | -------------------------------------------------------------------------------- /src/img/accept_change.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/accept_change.png -------------------------------------------------------------------------------- /src/img/activityStateDiagram.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/activityStateDiagram.jpeg -------------------------------------------------------------------------------- /src/img/always_use_code_view.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/always_use_code_view.png -------------------------------------------------------------------------------- /src/img/android_str_mismatch.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/android_str_mismatch.jpg -------------------------------------------------------------------------------- /src/img/apk_analyzer_ref.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/apk_analyzer_ref.jpeg -------------------------------------------------------------------------------- /src/img/are_notification_enabled.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/are_notification_enabled.jpg -------------------------------------------------------------------------------- /src/img/bookmarks_as.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/bookmarks_as.gif -------------------------------------------------------------------------------- /src/img/bookmarks_mnemonic_as.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/bookmarks_mnemonic_as.gif -------------------------------------------------------------------------------- /src/img/breakpoint_logs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/breakpoint_logs.jpg -------------------------------------------------------------------------------- /src/img/build_single_config.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/build_single_config.jpg -------------------------------------------------------------------------------- /src/img/dont_specify_buildtoolsversion.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/dont_specify_buildtoolsversion.jpg -------------------------------------------------------------------------------- /src/img/encode_special_1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/encode_special_1.gif -------------------------------------------------------------------------------- /src/img/encode_special_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/encode_special_2.png -------------------------------------------------------------------------------- /src/img/encode_special_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/encode_special_3.png -------------------------------------------------------------------------------- /src/img/extract_native_libs.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/extract_native_libs.jpg -------------------------------------------------------------------------------- /src/img/fold_line_like_this.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/fold_line_like_this.gif -------------------------------------------------------------------------------- /src/img/github_banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/github_banner.png -------------------------------------------------------------------------------- /src/img/group_recent_projects.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/group_recent_projects.jpg -------------------------------------------------------------------------------- /src/img/inject_vars_in_manifest.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/inject_vars_in_manifest.png -------------------------------------------------------------------------------- /src/img/live_template_wrapll_1.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/live_template_wrapll_1.gif -------------------------------------------------------------------------------- /src/img/live_template_wrapll_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/live_template_wrapll_2.png -------------------------------------------------------------------------------- /src/img/live_template_wrapll_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/live_template_wrapll_3.png -------------------------------------------------------------------------------- /src/img/making_methods_visible_for_testing.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/making_methods_visible_for_testing.jpg -------------------------------------------------------------------------------- /src/img/manifest-merged.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/manifest-merged.png -------------------------------------------------------------------------------- /src/img/mergetaginlayout.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/mergetaginlayout.jpg -------------------------------------------------------------------------------- /src/img/modified_default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/modified_default.png -------------------------------------------------------------------------------- /src/img/multiline_todo_comment.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/multiline_todo_comment.png -------------------------------------------------------------------------------- /src/img/proguard_rules_apk_analyzer.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/proguard_rules_apk_analyzer.gif -------------------------------------------------------------------------------- /src/img/quicklookup_def.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/quicklookup_def.gif -------------------------------------------------------------------------------- /src/img/region_cmt.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/region_cmt.gif -------------------------------------------------------------------------------- /src/img/region_cmt_template.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/region_cmt_template.gif -------------------------------------------------------------------------------- /src/img/restore_default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/restore_default.png -------------------------------------------------------------------------------- /src/img/running_hierarchy_viewer.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/running_hierarchy_viewer.jpg -------------------------------------------------------------------------------- /src/img/selectiverun.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/selectiverun.gif -------------------------------------------------------------------------------- /src/img/set_xml_as_preferred.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/set_xml_as_preferred.jpg -------------------------------------------------------------------------------- /src/img/testing_doze_mode.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/testing_doze_mode.jpg -------------------------------------------------------------------------------- /src/img/thread_annotations.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/thread_annotations.jpg -------------------------------------------------------------------------------- /src/img/unmodified_default.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nisrulz/android-tips-tricks/133dcae244c0386a4a31745f057037dd7511431f/src/img/unmodified_default.png -------------------------------------------------------------------------------- /src/introduction.md: -------------------------------------------------------------------------------- 1 | ![Image](img/github_banner.png) 2 | 3 | Cheatsheet about tips and tricks for Android Development 4 | 5 | This is a simple set of tips and tricks regarding Android Development which I have gathered from various sources. It helps me direct other android devs in my community regarding stuff each android dev should know about. It is also there for me to keep track of anything I either learn on my own or from other sources now and then when browsing the internet. 6 | 7 | Contributions are always welcome, hoping people will help me in growing this. To contribute, simply open up a PR with the changes. 8 | 9 | ### Show some ♥️ and 🌟 the repo to support the project 10 | 11 | [![GitHub stars](https://img.shields.io/github/stars/nisrulz/android-tips-tricks.svg?style=social&label=Star)](https://github.com/nisrulz/android-tips-tricks) [![GitHub forks](https://img.shields.io/github/forks/nisrulz/android-tips-tricks.svg?style=social&label=Fork)](https://github.com/nisrulz/android-tips-tricks/fork) [![GitHub watchers](https://img.shields.io/github/watchers/nisrulz/android-tips-tricks.svg?style=social&label=Watch)](https://github.com/nisrulz/android-tips-tricks) [![GitHub followers](https://img.shields.io/github/followers/nisrulz.svg?style=social&label=Follow)](https://github.com/nisrulz/android-tips-tricks) 12 | 13 | ### Featured in 14 | 15 | [![Android Weekly](https://img.shields.io/badge/Android%20Weekly-%23221-blue.svg)](http://androidweekly.net/issues/issue-221) [![AndroidDev Digest](https://img.shields.io/badge/AndroidDev%20Digest-%23110-blue.svg)](https://www.androiddevdigest.com/digest-110/) [![awesome-android](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/JStumpp/awesome-android#resources) 16 | 17 | **Also included in** 18 | 19 | - [Awesome Android Newsletter #Issue 16](https://android.libhunt.com/newsletter/16) 20 | 21 | #### Credits 22 | 23 | This curated cheatsheet includes tips and tricks that I have been following in my workflow as well as those being suggested/followed by other android devs worldwide.I have tried to add direct links wherever I could remember, giving people due credit who have explained the concepts. If you think I have missed any, then either send a PR or open an issue and I will fix it asap. 24 | 25 | If you appreciate my work, consider [buying me](https://www.paypal.me/nisrulz/5usd) a cup of ☕️ to keep me recharged 🤘🏼 [[PayPal](https://www.paypal.me/nisrulz/5usd)] 26 | 27 | [![Twitter Follow](https://img.shields.io/twitter/follow/nisrulz.svg?style=social)](https://twitter.com/nisrulz) 28 | -------------------------------------------------------------------------------- /src/learning-resources.md: -------------------------------------------------------------------------------- 1 | # Learning Resources 2 | 3 | - [Adhere to the coding guidelines](https://github.com/ribot/android-guidelines/blob/master/project_and_code_guidelines.md) 4 | 5 | - **Checkout [Android Dialogs](https://www.youtube.com/channel/UCMEmNnHT69aZuaOrE-dF6ug/feed)** 6 | Short byte sized android interview videos with experts. 7 | 8 | - **Checkout [Google's Udacity Android courses](https://www.udacity.com/courses/android)** 9 | 10 | Free courses and (paid) Nanodegree programs aimed at beginners up to advanced Android developers taught by professionals. 11 | 12 | - **Checkout [CodePath Android Cliffnotes](https://guides.codepath.com/android)** 13 | 14 | It is the central crowdsourced resource for complete and up-to-date practical Android developer guides for any topic. 15 | 16 | - **[Read the Effective Java by Joshua Bloch](https://www.amazon.ca/Effective-Java-2nd-Joshua-Bloch/dp/0321356683)** 17 | 18 | - [Cheatsheet/Summary](https://github.com/HugoMatilla/Effective-JAVA-Summary) 19 | 20 | - **[Subscribe to Caster.io](https://caster.io/)** 21 | 22 | Bite-sized Android development videos 23 | 24 | - **Bookmark these sites for staying upto date** 25 | - [Android Developers - Youtube Channel](https://www.youtube.com/user/androiddevelopers/videos) 26 | - [Android Niceties - UI Showcase](http://androidniceties.tumblr.com/) 27 | - [Material Design Specs](https://material.google.com/) 28 | - [Material Components](https://material.io/components/) 29 | - [Everything About Material Design](https://material.io/) 30 | - [Platform Version Distribution](https://developer.android.com/about/dashboards/index.html#Platform) 31 | - [Android Studio Release Notes](https://sites.google.com/a/android.com/tools/recent) 32 | - [Android Developers Blog](https://android-developers.blogspot.in/) 33 | - [AndroidDev-Reddit](https://www.reddit.com/r/androiddev) 34 | - [Github Trending Java Projects](https://github.com/trending?l=java&since=weekly) 35 | - [Stackoverflow-Android tag](https://stackoverflow.com/questions/tagged/android) 36 | - [Support Library History](https://developer.android.com/topic/libraries/support-library/revisions.html) 37 | - [Android Conferences](https://androidstudygroup.github.io/conferences/) 38 | - [Android Dev Docs](https://developer.android.com/reference/packages.html) 39 | - [Material Up - DesignShowcase](http://www.material.uplabs.com/) 40 | - [Dribbble - MaterialDeisgnShowcase](https://dribbble.com/tags/material_design) 41 | - [UltimateAndroidReference](https://github.com/aritraroy/UltimateAndroidReference) 42 | 43 | 44 | - **Bookmark these sites for keeping track of Android Support Libs(AOSP AndroidX)** 45 | 46 | - [File a bug/issue for Android KTX](https://issuetracker.google.com/issues/new?component=396204&template=1082185) 47 | - [Info regarding sending a PR to AOSP AndroidX Libs](https://android.googlesource.com/platform/frameworks/support/) 48 | - [Stuff worked on for AOSP AndroidX](https://android-review.googlesource.com/q/project:platform%252Fframeworks%252Fsupport+branch:androidx-master-dev) 49 | 50 | - **[Checkout the Testing guide](https://github.com/ravidsrk/android-testing-guide)** 51 | 52 | - **Subscribe to newsletters to stay upto date** 53 | 54 | - [Android Weekly](http://androidweekly.net/) - Free newsletter that helps you to stay cutting-edge with your Android Development 55 | - [AndroidDevDigest](https://www.androiddevdigest.com/) - A Handcrafted Weekly #AndroidDev Newsletter 56 | - [Infinium #AndroidSweets](https://androidsweets.ongoodbits.com/) - Fresh news from Droid zone 57 | - [Kotlin Weekly](http://us12.campaign-archive2.com/home/?u=f39692e245b94f7fb693b6d82&id=93b2272cb6) - Free newsletter to stay uptodate with Kotlin Development 58 | -------------------------------------------------------------------------------- /src/make-better-choices-while-coding.md: -------------------------------------------------------------------------------- 1 | # Make better choices while coding 2 | 3 | - **Use OkHttp over HttpUrlConnect** 4 | 5 | HttpUrlConnect suffers from [quite some bugs](https://android-developers.blogspot.in/2011/09/androids-http-clients.html). [Okhttp](https://square.github.io/okhttp/) solves them in a more elegant manner. [[Reference Link]](https://corner.squareup.com/2013/05/announcing-okhttp.html) 6 | 7 | * **Use [Pidcat](https://github.com/JakeWharton/pidcat) for a better log reading experience** 8 | 9 | * **Use some Version Control System(VCS) like [Git](https://git-scm.com/)** 10 | 11 | * **Use [ClassyShark](https://github.com/google/android-classyshark)** 12 | 13 | It is a standalone tool for Android Devs used to browse any Android executable and show important info such as class interfaces and members, dex counts and dependencies 14 | 15 | * **Use [Stetho](https://github.com/facebook/stetho)** 16 | 17 | Debug your android apps using Chrome Dev Tools. Includes tools like Network Monitor, Shared Preference explorer etc. 18 | 19 | * **Use [Battery Historian](https://github.com/google/battery-historian)** 20 | 21 | A tool to analyze battery consumers using Android "bugreport" files. 22 | 23 | * **Always use a constant version value like "1.2.0"** 24 | 25 | Avoid using `+` when specifying the version of dependencies. 26 | 27 | - Keeps one secured from unexpected API changes in the dependency. 28 | - Avoids doing an extra network call for the checking latest version of each dependency on every build. 29 | 30 | * **Use [Handler instead of a TimerTask](http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/)** 31 | 32 | * **[Do not use your own personal email for Google Play Developer Account](https://www.reddit.com/r/Android/comments/2hywu9/google_play_only_one_strike_is_needed_to_ruin_you/)** 33 | * **Use Vectors instead of PNG** 34 | 35 | If you do **have** to use png, compress them. Take a look at [TinyPNG](https://tinypng.com). 36 | 37 | * **Learn about some architecture such as MVP or Clean** 38 | 39 | * **Try to understand and follow TDD (Test Driven Development)** 40 | 41 | * **Follow the DRY principle** 42 | DRY = Do not Repeat Yourself 43 | 44 | * **[Package by Feature, not layers](https://medium.com/the-engineering-team/package-by-features-not-layers-2d076df1964d)** 45 | 46 | * **[Learn about Dependency Resolution](http://crushingcode.co/the-curious-case-of-dependency-conflicts/)** 47 | 48 | With the speed android dependencies update, sooner or later you are going to encounter some sort of dependency conflict. The solution is making use of Dependency Resolution. [Official Reference](https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html) 49 | 50 | 51 | * **[Find and STOP leaking memory in your android app](http://blog.nimbledroid.com/2016/09/06/stop-memory-leaks.html)** 52 | 53 | * **[If you’re creating a gradient in xml with a part being completely transparent, be really careful when using `@android:color/transparent`](https://android.jlelse.eu/android-dev-tip-3-99da754151ad#.clbqzz3zh)** 54 | 55 | * **[Follow a standard naming convention for your resources](http://jeroenmols.com/blog/2016/03/07/resourcenaming/)** 56 | 57 | * **Use a proper .gitignore in your Android Projects, [Check it here](/android.gitignore)** 58 | 59 | * **[Use LeakCanary to detect memory leaks in your app](https://github.com/square/leakcanary)** - Its a memory leak detection library for Android and Java. 60 | 61 | * **Enable gradle to automatically download missing platforms in android sdk** 62 | 63 | Set the below property in your global `gradle.properties` file 64 | 65 | ``` 66 | android.builder.sdkDownload=true 67 | ``` 68 | 69 | > This is an experimental option and it only downloads build tools and platforms, but doesn't actually update Google or Support repository [[Bug Ref]](https://code.google.com/p/android/issues/detail?id=212309) 70 | 71 | 72 | * **Clear your gradle cache if you think that bundled support and google play services lib in android sdk are inconsistent** 73 | 74 | - Goto `~/.gradle/caches/` and delete everything inside the `cache` folder. 75 | - Open SDK Manager and resync all support libs and google play services 76 | - Next re-sync your project 77 | - Everything should become consistent and functional. 78 | 79 | * **Use [`alfi`](https://github.com/cesarferreira/alfi) to find the gradle dependency statement for a library** 80 | 81 | > Its basically the command line version of [Gradle, Please](gradleplease.appspot.com) which is a web hosted. 82 | 83 | - Run 84 | 85 | ```bash 86 | alfi name_of_library 87 | ``` 88 | 89 | - Copy the desired library 90 | - Paste in your build.gradle 91 | 92 | * **Use [`dryrun`](https://github.com/cesarferreira/dryrun) to test a library directly** 93 | 94 | - Just Run 95 | 96 | ```bash 97 | dryrun REMOTE_GIT_URL 98 | ``` 99 | 100 | 101 | * **Use an abtracted [Logger](/Logger.java) class** 102 | 103 | * **If you want to automatically initialize your library, use a Content Provider** [[Read how Firebase does it - Ref Link]](https://firebase.googleblog.com/2016/12/how-does-firebase-initialize-on-android.html) 104 | 105 | * **Reduce installed app size with `"android:extractNativeLibs:false"` in ``** [[Ref Link]](https://medium.com/@wkalicinski/smallerapk-part-8-native-libraries-open-from-apk-fc22713861ff#.bajqmlshi) 106 | 107 | > This will essentially prevent the system from creating a second copy of the .so files and fix the System.loadLibrary call so it’s able to find and open native libs straight from the APK, no code changes on your part required. 108 | 109 | * **Selectivily execute a specific method in Android Studio** [[Ref Link]](https://twitter.com/tasomaniac/status/820019068140945408) 110 | 111 | ![Image](img/selectiverun.gif) 112 | 113 | * **Did you get one of these Google Play Developer Policy Violation Emails? Worry not, generate a Privacy Policy for your android app** [[Ref ink]](https://medium.com/@ali.muzaffar/did-you-get-one-of-these-google-play-developer-policy-violation-emails-6c529ceb082d#.f10upj3fy) 114 | 115 | - Take a look at [App Privacy Policy Generator](https://app-privacy-policy-generator.firebaseapp.com/), a web app to generate a generic privacy policy for your app. 116 | 117 | * **Activity LifeCycle** [[Ref Link](https://www.bignerdranch.com/blog/android-activity-lifecycle-onStop/)] 118 | 119 | ![diagram](img/activityStateDiagram.jpeg) 120 | 121 | * **Tip about `onSaveInstanceState()`** 122 | `onSaveInstanceState()` is called **_only when the OS decides to kill the `Activity` instance_**. It will not be called when Activity is explicitly killed i.e User pressed back button or `finish()` is called from code. 123 | 124 | * **[If you are into building Android Libraries, then read here for more tips](https://android.jlelse.eu/things-i-wish-i-knew-when-i-started-building-android-sdk-libraries-dba1a524d619)** 125 | 126 | * **[Read about whats in an APK here](http://crushingcode.nisrulz.com/whats-in-the-apk/)** 127 | 128 | * **[Input some text in an editfield in a running emulator from your keyboard ](http://fragmentedpodcast.com/episodes/77/)** 129 | 130 | ```gradle 131 | adb shell input text "keyboard text" 132 | ``` 133 | 134 | * **Use [`areNotificationsEnabled()`]() from [`NotificationManagerCompat`](https://developer.android.com/reference/android/support/v4/app/NotificationManagerCompat.html#areNotificationsEnabled) to detect whether your users blocked your Notifications** [[Ref Link](https://twitter.com/tasomaniac/status/851888395152392193/photo/1)] 135 | 136 | * **Don't hard-code encryption keys, a simple grep for `"Ljavax/crypto"` reveals them in bytecode** [[Ref Link](https://twitter.com/molsjeroen/status/851708885782204417)] 137 | 138 | * **Intents have a limited payload size (1Mb), don't serialize and attach entire file to it** [[Ref Link](https://twitter.com/molsjeroen/status/851353828905627648)] 139 | 140 | * **Always copy a file before sending it as intent URI. Receiving app could edit it & send a canceled result** [[Ref Link](https://twitter.com/molsjeroen/status/851354820883689473)] 141 | 142 | * **Use `http://` as scheme for app deeplinks, they are more universal & when app not installed drive users to a domain you own** [[Ref Link](https://twitter.com/molsjeroen/status/851349683440111616)] 143 | 144 | * **Use below to display your app launch time** [[Ref Link](https://twitter.com/molsjeroen/status/851367439996784640)] 145 | 146 | ```bash 147 | adb shell am start -W /. 148 | ``` 149 | 150 | * **[Use activity-alias or your launcher icons will disappear when renaming/moving your MainActivity](https://medium.com/@Mauin/the-case-of-disappearing-launcher-icons-657c3663b9d3)** 151 | 152 | * To enable `aapt2` set below in gradle properties 153 | 154 | ```gradle 155 | android.enableaapt2=true 156 | ``` 157 | 158 | * To testout doze mode, trigger it using `adb` [[Ref Link](https://developer.android.com/training/monitoring-device-state/doze-standby.html#testing_doze) 159 | 160 | ```bash 161 | adb shell dumpsys deviceidle force-idle 162 | ``` 163 | 164 | * Thumb rule regarding setting `compileSdkVersion`, `minSdkVersion` and `targetSdkVersion` 165 | 166 | > `minSdkVersion` (lowest possible) <= `targetSdkVersion` == `compileSdkVersion` (latest SDK) 167 | 168 | - Google released an option to include OSS license activity in your app, use that to attribute credits to the OSS libs in your app [[Ref Link](https://developers.google.com/android/guides/opensource)] 169 | 170 | > [Checkout a working example here](https://github.com/nisrulz/android-examples/tree/master/OSSLicenseActivity) 171 | 172 | - Make Android Studio render `` layouts correctly by specifying the layout type with the tools:parentTag attribute [[Ref Link](https://twitter.com/m_evans10/status/907635918550511617)] 173 | 174 | ![diagram](img/mergetaginlayout.jpg) 175 | 176 | - Checkout the Background Execution Limits on Android Oreo and update your app to work with the restrictions [[Ref Link](https://medium.com/exploring-android/exploring-background-execution-limits-on-android-oreo-ab384762a66c)] 177 | 178 | - To take good screenshots with clean status bar use the [**Demo Mode**](https://android.googlesource.com/platform/frameworks/base/+/master/packages/SystemUI/docs/demo_mode.md) in Android [[Ref Link](https://android.jlelse.eu/clean-your-status-bar-like-a-pro-76c89a1e2c2f)] 179 | 180 | - Steps 181 | 182 | 1. Enable Demo Mode 183 | 184 | ```bash 185 | adb shell settings put global sysui_demo_allowed 1 186 | ``` 187 | 188 | 1. Enable/disable icons by running the right command 189 | 190 | ```bash 191 | // display time 12:00 192 | adb shell am broadcast -a com.android.systemui.demo -e command clock -e hhmm 1200 193 | 194 | // Display full mobile data without type 195 | adb shell am broadcast -a com.android.systemui.demo -e command network -e mobile show -e level 4 -e datatype false 196 | 197 | // Hide notifications 198 | adb shell am broadcast -a com.android.systemui.demo -e command notifications -e visible false 199 | 200 | // Show full battery but not in charging state 201 | adb shell am broadcast -a com.android.systemui.demo -e command battery -e plugged false -e level 100 202 | ``` 203 | 204 | 1. Run app and take screenshots 205 | 206 | 1. Exit demo mode once you are done 207 | 208 | ```bash 209 | adb shell am broadcast -a com.android.systemui.demo -e command exit 210 | ``` 211 | 212 | - To record video of your android device [[Ref Link](https://dev.to/aneesahammed/best-way-to-record-your-screen-on-android)] 213 | 214 | ```bash 215 | adb shell && screenrecord /sdcard/download/fileName.mp4 216 | ``` 217 | 218 | > Hit `Ctrl+C` to exit/stop recording 219 | > 220 | > Recorded video file is saved at the location mentioned in the command on the device itself. 221 | 222 | - Use Dao inheritance to reduce the amount of boilerplate code [[Ref Link](https://gist.github.com/florina-muntenescu/1c78858f286d196d545c038a71a3e864)] 223 | 224 | - Instead of using `getActivity()` in fragment, keep a habit of getting context from `onAttach()`. [[Ref Link](https://twitter.com/ravi_rupareliya/status/920881340245073920)] 225 | 226 | - Avoid setting a background in every view/fragment as it likely causes overdraw. [[Ref Link](https://twitter.com/molsjeroen/status/923543967978881025)] 227 | 228 | - `View.getWidth() = 0?` That's because your view hasn't been layout yet, use globallayoutListener to know layout done. [[Ref Link](https://twitter.com/molsjeroen/status/923542864877047808)] 229 | 230 | - Android never kills activities, it only kills processes. When low memory the lowest priority ranked will be killed.[[Ref Link](https://twitter.com/molsjeroen/status/923510846696951809)] 231 | 232 | - [Use `.([filename].java:[line])` in your log statements to make them clickable in Android Studio and Intellij IDEA.](https://medium.com/@tauno/android-studio-pro-tip-go-to-source-from-logcat-output-f13bf46411b5) 233 | 234 | - Use `-whyareyoukeeping class com.jeroenmols.MyClass` to figure out why certain a class wasn't removed.[[Ref Link](https://twitter.com/molsjeroen/status/905713748173881345)] 235 | 236 | - Use certificate pinning to resist impersonation by attackers using mis-issued or otherwise fraudulent certificates, when making requests from your app. [[Ref Link](https://dev.to/mplacona/certificate-pinning-in-android)] 237 | 238 | - Do download the latest emulator using CLI 239 | 240 | ``` 241 | cd /tools/bin 242 | ./sdkmanager --channel=3 emulator 243 | ``` 244 | 245 | To check the version of emulator, use `./sdkmanager --channel=3 emulator` 246 | 247 | - **[Checkout some tricks when using Android Strings in XML](https://android.jlelse.eu/android-strings-xml-tips-tricks-52b0c820cf7a)** 248 | 249 | - Cleanup your Gradle caches by deleting files not accessed within the last month [[Ref Link](https://github.com/gradle/gradle/issues/2304)] 250 | 251 | ``` 252 | find ~/.gradle -type f -atime +30 -delete 253 | find ~/.gradle -type d -mindepth 1 -empty -delete 254 | ``` 255 | 256 | > To check the size of your gradle cache, run: `du -sh ~/.gradle` 257 | 258 | - **[Checkout some cool tricks when using `tools:` attribute in your android layouts, such as sample data and recyclerview item layout previews](https://blog.stylingandroid.com/tool-time-part-1-2/)** 259 | 260 | - Remove all debug log statements from the release build using the below proguard rules. (app's build.gradle should have `minifyEnabled true` set for this to work) 261 | 262 | ``` 263 | # Remove all debug logs 264 | -assumenosideeffects class android.util.Log { 265 | public static *** d(...); 266 | } 267 | ``` 268 | 269 | > The above snippet is usually appended to contents of app/proguard-rules.pro file 270 | 271 | - **[Should I use Enums in Android?](https://trevore.com/post/should-i-use-enums-in-android/)** 272 | 273 | **tl;dr** 274 | 275 | - If you need code to be very performant integer constants may be the way to go 276 | ```java 277 | public class Operator { 278 | public static final int ADD = 1; 279 | public static final int SUBTRACT = 2; 280 | public static final int MULTIPLY = 3; 281 | public static final int DIVIDE = 4; 282 | } 283 | ``` 284 | - Use Enums because 285 | 286 | - Are type-safe, so you can only use valid enum types 287 | - Provide better code readability 288 | - Can implement interfaces 289 | - Support polymorphic behavior 290 | - In some really trivial cases, Proguard can optimize Enums into integer constants for you [[Ref Link](https://www.guardsquare.com/en/proguard/manual/optimizations)] 291 | - Performance difference rarely makes a difference. 292 | 293 | ```java 294 | public enum Operators { 295 | Add, Subtract, Multiply, Divide 296 | } 297 | ``` 298 | 299 | - The string resource `android.R.string.yes` doesnot yield string "Yes" instead it yields "Ok". Similarly the string resource `android.R.string.no` doesnot yield string "No" instead it yields "Cancel" [[Ref Link](https://twitter.com/mandybess/status/971901727711535105)] 300 | 301 | ![string resource](img/android_str_mismatch.jpg) 302 | 303 | - Don’t want generated files in your AS search results? Go to `Preferences -> File Types -> Ignore files and folders` and add the pattern to ignore - e.g. `*.dex;*.class;` [[Ref Link](https://twitter.com/marianeum/status/1021385021695852544)] 304 | 305 | - If you uncheck “Suspend” and check “Evaluate and Log” in breakpoint menu, the breakpoint will print evaluated statement into the uncluttered “Console” window. No need for recompile due to added Log.d statements anymore [[Ref Link](https://twitter.com/jernejv/status/1021456131925979136)] 306 | 307 | ![Breakpoint Logs](img/breakpoint_logs.jpg) 308 | 309 | - To measure how long a method took to execute, you can use `TimingLogger` class. [[Ref Link](https://developer.android.com/reference/android/util/TimingLogger)] 310 | 311 | - Typical Usage 312 | ```java 313 | TimingLogger timings = new TimingLogger(TAG, "methodA"); 314 | // ... do some work A ... 315 | timings.addSplit("work A"); 316 | // ... do some work B ... 317 | timings.addSplit("work B"); 318 | // ... do some work C ... 319 | timings.addSplit("work C"); 320 | timings.dumpToLog(); 321 | ``` 322 | - Output 323 | ``` 324 | D/TAG ( 3459): methodA: begin 325 | D/TAG ( 3459): methodA: 9 ms, work A 326 | D/TAG ( 3459): methodA: 1 ms, work B 327 | D/TAG ( 3459): methodA: 6 ms, work C 328 | D/TAG ( 3459): methodA: end, 16 ms 329 | ``` 330 | 331 | - If you're working with Android Things and you don't have an extrenal screen for your device, install [scrcpy](https://github.com/Genymobile/scrcpy) and use it to see what's going on your Android IoT device. It works a charm over wireless adb. [[Ref Link](https://twitter.com/Tunji_D/status/1019985858575978497)] 332 | 333 | - Android Studio has this weird behaviour that it allows to edit its default code style, which leads to a weird side-effect. If you open your pre-setup project(with set codestyle and copyright configs) in Android Studio it will delete all pre-setup codestyle and copyright profile in this project. This is every much evident if you checked in your configs into git for sharing purpose, which is lost immediately as soon as you open the project 334 | 335 | ```bash 336 | deleted: .idea/codeStyles/Project.xml 337 | deleted: .idea/codeStyles/codeStyleConfig.xml 338 | deleted: .idea/copyright/profiles_settings.xml 339 | deleted: .idea/copyright/copyright.xml 340 | ``` 341 | 342 | To fix that please follow along as below: [All thanks to [Said Tahsin Dane](https://twitter.com/tasomaniac) for the solution] 343 | 344 | - We first need to verify that your `Default` codestyle isn't modified. To check that please open Android Studio with any project except your pre-setup(with set codestyle and copyright configs) project. Then navigate to `Preferences>Edior>Codestyle` and check if your code scheme has `Default` in **BLUE** color (this means it is modified). 345 | 346 | ![modified_default](img/modified_default.png) 347 | 348 | - However if it is not colored **BLUE**, you are good and you can go ahead to open your pre-setup(with set codestyle and copyright configs) project and everything should be pre-setup for you. 349 | 350 | - If it is modified (colored **BLUE**), then click on the cog icon and select `Restore Default` 351 | 352 | ![restore_default](img/restore_default.png) 353 | 354 | - After you hit that option, simply accept the change 355 | 356 | ![accept_change](img/accept_change.png) 357 | 358 | - Once done, you will see your Default is no more colored **BLUE** or modified, which means you are good 359 | 360 | ![unmodified_default](img/unmodified_default.png) 361 | 362 | - Now simply go ahead and open your pre-setup(with set codestyle and copyright configs) project and everything should be pre-setup for you. 363 | 364 | - If you add `android:sharedUserId` to an already published app, the app data will be cleared for all users that install your upgrade (because Android changes the process). So if you ever intend to use it, you must add it before publishing your app [[Ref Link](https://twitter.com/molsjeroen/status/1022840282012966912)] 365 | 366 | - When opening up methods for testing, use otherwise to still hide it from code complete.[[Tweet Link](https://twitter.com/molsjeroen/status/996684391891038208), [Ref Link](https://plugins.jetbrains.com/plugin/9952-visiblefortesting)] 367 | 368 | ![making_methods_visible_for_testing](img/making_methods_visible_for_testing.jpg) 369 | 370 | - You can group your recent Android Studio projects, and add icons to them [[Ref Link](https://twitter.com/Flashmasterdash/status/996309558120402954/photo/1)] 371 | 372 | ![group_recent_projects](img/group_recent_projects.jpg) 373 | 374 | - Only build a single configuration to speed up debug builds. [[Ref Link](https://twitter.com/molsjeroen/status/973615936279281666)] 375 | 376 | ![build_single_config](img/build_single_config.jpg) 377 | 378 | - Avoid the annoying jump to Design tab while editing XML. Prefer XML editor under Settings [[Ref Link](https://twitter.com/rakshakhegde/status/907913497115160576)] 379 | 380 | ![set_xml_as_preferred](img/set_xml_as_preferred.jpg) 381 | 382 | - Reduce installed app size with `android:extractNativeLibs="false"` in [[Tweet Link](https://twitter.com/molsjeroen/status/819457612005736448), [Ref Link](https://medium.com/@wkalicinski/smallerapk-part-8-native-libraries-open-from-apk-fc22713861ff)] 383 | 384 | 385 | 386 | 387 | - Improve Android Studio code inspections with Thread annotations [[Tweet Link](https://twitter.com/molsjeroen/status/989447750176706560), [Ref Link](https://developer.android.com/studio/write/annotations#thread-annotations)] 388 | 389 | 390 | 391 | - Use `adb` to put a phone into doze mode for testing [[Tweet Link](https://twitter.com/molsjeroen/status/872007858300362752), [Ref Link](https://developer.android.com/training/monitoring-device-state/doze-standby#testing_doze)] 392 | 393 | 394 | 395 | - Use `areNotificationsEnabled()` from `NotificationManagerCompat` to detect whether your users blocked your Notifications [[Tweet Link](https://twitter.com/tasomaniac/status/851888395152392193), [Ref Link]()] 396 | 397 | 398 | 399 | - `Activity.runOnUiThread` is just a convenient wrapper of `Handler.post`; don't pass around `Activity` just so you can use it. [[Ref Link](https://twitter.com/devunwired/status/193385939115053056)] 400 | 401 | - Define your interfaces with the highest possible option that will suffice. Don't use an `Activity` when a Context will do. [[Ref Link](https://twitter.com/devunwired/status/193102514047041538)] 402 | 403 | - If you're not building a replacement for the dialer, use `ACTION_DIAL` _not_ `ACTION_CALL` to initiate a call. [[Ref Link](https://twitter.com/kdarty/status/20971150330)] 404 | 405 | - Requesting updates from a system service may drain battery, so register for updates in onResume and unregister in onPause. [[Ref Link](https://twitter.com/nisrulz/status/818356887041118208)] 406 | 407 | - Hierarchy Viewer won’t run on prod devices, if however u want to run it then follow below steps [[Tweet Link](https://twitter.com/nisrulz/status/800016465805983744), [Ref Link](https://developer.android.com/studio/profile/hierarchy-viewer#setup)] 408 | 409 | ![running_hierarchy_viewer](img/running_hierarchy_viewer.jpg) 410 | 411 | - Variable and `init` block declaration order in Kotlin, actually matters :) if you want to use a variable inside init {} initialize it before it. 412 | 413 | - When comparing intents it does _not_ compare any extra data included in the intents [[Tweet Link](https://twitter.com/scottyab/status/388393250286870529), [Ref Link]()] 414 | 415 | - To show a ringtone picker to the user, use the `ACTION_RINGTONE_PICKER` intent to launch the picker as a subactivity. [[Ref Link](https://twitter.com/pareshmayani/status/359390161399853056)] 416 | 417 | - Want to remove focusState on an item in GridView? Try: `android:listSelector="#00000000"` [[Ref Link](https://twitter.com/BSkretting/status/176655811899166721)] 418 | 419 | - You can generate the **proguard** keep rules via the APK Analyzer inside Android Studio. [[Ref Link](https://medium.com/androiddevelopers/troubleshooting-proguard-issues-on-android-bce9de4f8a74)] 420 | 421 | ![proguard_rules_apk_analyzer](img/proguard_rules_apk_analyzer.gif) 422 | 423 | - When viewing an Android Manifest, there is a tab at the bottom that allows you to see the merged manifest. Use this to inspect the merged manifest and find conflicts. [[Ref Link](https://developer.android.com/studio/build/manifest-merge#inspect_the_merged_manifest_and_find_conflicts)] 424 | 425 | ![manifest-merged](img/manifest-merged.png) 426 | 427 | - In the APK analyzer in Android Studio, classes/members listed in italic are only references, not definitions. If it's in italics, it's defined in another DEX file (or the SDK). [[Ref Link](https://twitter.com/jebstuart/status/1093502138943197191)] 428 | 429 | ![apk_analyzer_ref](img/apk_analyzer_ref.jpeg) 430 | 431 | - To be able to write multiline Todo comments, simply indent by 1 tab from second line onwards. [[Ref Link](https://twitter.com/Saketme/status/1156667576946253825)] 432 | 433 | ![multiline_todo_comment](img/multiline_todo_comment.png) 434 | 435 | - You can get rid of a lot of noise in the Logcat, by Right Clicking a selected text > "Fold lines like this" option!. [[Ref Link](https://twitter.com/nisrulz/status/1197253137683357698)] 436 | 437 | ![fold_line_like_this](img/fold_line_like_this.gif) 438 | 439 | - You know how you can group ur code inside IDEs such as Android Studio and IntelliJ IDEA by using the `region` and `endregion` comment blocks. Turns out you can use the same trick to group inside XML files such as for layout, strings, styles, colors xml files [[Ref Tweet](https://web.archive.org/web/20200614000022/https://twitter.com/nisrulz/status/1271954906015023104)] 440 | 441 | ![region_cmt](img/region_cmt.gif) 442 | 443 | - How many of you have had issue with special characters (&,<, >, etc) in your strings.xml file? Did you know there is an action called "Encode XML/HTML Special Characters" inside Android Studio that can escape those characters for you! [[Ref Tweet](https://twitter.com/nisrulz/status/1288498430525005824)] 444 | 445 | ![encode_special_1](img/encode_special_1.gif) 446 | 447 | - The option is also avaliable under **Edit menu** drop down 448 | 449 | ![encode_special_2](img/encode_special_2.png) 450 | 451 | - In case the issue is in just one line, you can also just `ALT+ENTER` to get contextual fix. 452 | 453 | ![encode_special_3](img/encode_special_3.png) -------------------------------------------------------------------------------- /src/misc.md: -------------------------------------------------------------------------------- 1 | # Misc 2 | 3 | ### **_Other Resources_** 4 | 5 | - [Google's Maven Repository](https://dl.google.com/dl/android/maven2/index.html) 6 | 7 | - **[Take care about copyright](http://jeroenmols.com/blog/2016/08/03/copyright/)** 8 | 9 | - **Checkout new android libraries** 10 | 11 | [Android Arsenal](https://android-arsenal.com/) - Android developer portal with tools, libraries, and apps 12 | 13 | - **Follow on Twitter** 14 | 15 | - [#AndroidDev](https://twitter.com/search?q=%23AndroidDev) 16 | 17 | - **Create a List on Twitter** 18 | 19 | - [Android List](https://twitter.com/nisrulz/lists/android) 20 | 21 | - **Fix issue with Audio getting worse on your Bluetooth Headset when starting Emulator** 22 | 23 | You can deal with this problem in 2 ways. 24 | 1. Using Terminal 25 | 26 | ```sh 27 | # i.e emulator -noaudio-avd Pixel_4a_API_31 28 | emulator -noaudio-avd 29 | ``` 30 | 31 | 2. Editing the config for Emulator 32 | 33 | Navigate to your existing Emulator and edit the `config.ini` file 34 | 35 | ```sh 36 | # Wipe Data + Cold Boot once 37 | hw.audioInput = no 38 | hw. audioOutput = no 39 | ``` 40 | Read an indepth article [here](https://blog.mmckenna.me/android-emulators-vs-bluetooth-headphones) 41 | -------------------------------------------------------------------------------- /src/podcasts.md: -------------------------------------------------------------------------------- 1 | # Podcasts to listen 2 | 3 | 1. [Fragmented](http://fragmentedpodcast.com/) 4 | 1. [Android Developer Podcasts](https://developer.android.com/podcasts) 5 | 6 | There are others too, but the above two are the popular ones, you can lookup more using tag `android` on sites offering Podcast Services. 7 | 8 | P.S : I use [Player.fm](https://player.fm/) to listen to these podcasts. They even have an [Android Client](https://play.google.com/store/apps/details?id=fm.player&hl=en), all for FREE. 9 | -------------------------------------------------------------------------------- /src/scrcpy.md: -------------------------------------------------------------------------------- 1 | # [scrcpy](https://github.com/genymobile/scrcpy) 2 | 3 | It is basically used to display and control your Android device and is the open source equivalent of [Vysor](http://www.vysor.io/). The good folks at [Genymotion](https://www.genymotion.com/) built this tool and then open sourced it (Open Source FTW). 4 | -------------------------------------------------------------------------------- /src/tips-if-you-use-kotlin.md: -------------------------------------------------------------------------------- 1 | # Tips if you use Kotlin 2 | 3 | - **Checkout [From Java to Kotlin](https://fabiomsr.github.io/from-java-to-kotlin/)** 4 | 5 | Cheatsheet when you come from Java to Kotlin. Very nice resource to compare the two languages. 6 | 7 | - **Checkout [Kotlin Style Guide](https://android.github.io/kotlin-guides/index.html) by Google** 8 | -------------------------------------------------------------------------------- /src/tips-regarding-uiux.md: -------------------------------------------------------------------------------- 1 | # Tips regarding UI/UX 2 | 3 | - **Motion** 4 | 5 | - Material Design uses real-world metaphors as its foundation. Objects in the real world don't move linearly, they move in curved paths and accelerate and decelerate according to the motion's properties. 6 | - As such, motion should also use such properties and animate objects so that the motion feels natural rather than forced 7 | - For example, a car leaving the screen in a movie starts off slowly, then accelerates till it's out of the frame. Similarly, views should be interpolated using classes like AccelerateInterpolator, FastOutSlowInInterpolator, etc. [[More Info]](https://developer.android.com/reference/android/animation/TimeInterpolator.html) 8 | - When changing the visibilities of views, if you add `android:animateLayoutChanges="true"` to the parent, you get a nice little animation for free. [[Ref Link](https://proandroiddev.com/the-little-secret-of-android-animatelayoutchanges-e4caab2fddec)] 9 | 10 | - **Typography** 11 | - While custom typefaces can be used for branding, it is essential to stick to Roboto and Noto if possible, especially for body text, due to their clarity and optimistic nature. 12 | - Roboto covers Latin, Greek and Cyrillic extended scripts, with Noto filling in for other language scripts [[More Info]](https://material.google.com/style/typography.html#) 13 | - Weight balancing is an important aspect of typography, the fundamental concept of which is that the larger a typeface is, the less its weight should be so that it doesn't appear too thick and balances its weight with smaller typefaces of higher weights 14 | - Typography should align to a 4dp baseline grid, and maintain a minimum contrast ratio of 4.5:1 based on luminance values, with a recommended ratio being 7:1. 15 | - The ideal reading length for large blocks of text is 40 to 60 characters per line. Anything less is too narrow and anything more is too wide. 16 | 17 | * **Icons** 18 | 19 | - Icons should be designed at 48dp, with 1dp edges, which equates to 20 | - 48px by 48px at mdpi 21 | - 72px by 72px at hdpi 22 | - 96px by 96px at xhdpi 23 | - 144px by 144px at xxhdpi 24 | - 192px by 192px at xxxhdpi 25 | - An additional icon of 512px by 512px should be designed for use on Google Play 26 | - Material icons, in addition to the base icon, should contain the following important elements 27 | - 1dp tinted edge at the top 28 | - 1dp shaded edge at the bottom 29 | - Contact shadow - a soft shadow around all edges of raised elements 30 | - Finish - a soft tint to provide surface lighting, fading from upper life to lower right [[More Info]](https://material.google.com/style/icons.html#icons-product-icons) 31 | 32 | * **Ripples** 33 | 34 | - When implementing Ripple Effect use `?attr/selectableItemBackground` instead of `?android:attr` ([Ref](https://twitter.com/pareshmayani/status/772061422729637893)) 35 | - When implementing Ripples contained within the view like Button, use ([Ref](https://twitter.com/pareshmayani/status/772268888931176448)) 36 | 37 | ```xml 38 | android:background="?attr/selectableItemBackground" 39 | ``` 40 | 41 | - When implementing Ripples that extend beyond the view's bounds like ImageView: ([Ref](https://twitter.com/pareshmayani/status/772269413290520576)) 42 | 43 | ```xml 44 | ?attr/selectableItemBackgroundBorderless 45 | ``` 46 | 47 | - **Other Points to Note** 48 | - Views should be aligned to Material Design's 8dp baseline grid and the keylines when possible. This gives the UI a sense of structure and hierarchy. [[More Info]](https://material.google.com/layout/metrics-keylines.html) 49 | - If you plan on keeping a reference to any ViewGroup (LinearLayout, FrameLayout, RelativeLayout, etc.), and you don’t want to use any methods specific to this particular type of Layout, keep it as a ViewGroup object. [[More Info]](https://android.jlelse.eu/android-pro-tip-1-443f423b4de6#.pklc9djmc) 50 | - While picking an accent color (if the brand already has one), pick a color complementary to the primary color so that the contrast is high enough 51 | -------------------------------------------------------------------------------- /src/use-code-completion-in-as.md: -------------------------------------------------------------------------------- 1 | # Speed code using code-completion 2 | 3 | ## Use Live Templates in Android Studio 4 | - `newInstance` - Generates the static `newInstance` function inside a Fragment 5 | - `Toast` - Generates `Toast.makeText(context, "", Toast.LENGTH_SHORT).show();` 6 | - `fbc` - findViewById with cast 7 | - `const` - Define a android style int constant 8 | - `logd` - Generates `Log.d(TAG, "");` 9 | - `logm` - Log current method name and its arguments. 10 | - `logr` - Log result of the current method 11 | - `logt` - static logtaf with current classname 12 | - `psf` - public static final 13 | - `sout` - Prints a string to System.out 14 | - `soutm` - Prints current class and method names to System.out 15 | - `soutp` - Prints method parameter names and values to System.out 16 | - `visible` - Set view visibility to VISIBLE 17 | - `gone` - Set view visibility to GONE 18 | - `noInstance` - private empty constructor to prohibit instance creation 19 | 20 | - There is a quick way to surround your layout with a Linear Layout via using a Live Template. You can create one called `wrapll` by setting it up [[Ref Link](https://twitter.com/nisrulz/status/1197666095886454789)] 21 | 22 | ![live_template_wrapll_2](img/live_template_wrapll_2.png) 23 | ![live_template_wrapll_3](img/live_template_wrapll_3.png) 24 | 25 | ...and use it as below 26 | 27 | ![live_template_wrapll_1](img/live_template_wrapll_1.gif) 28 | 29 | > You can create more based on your usecase 😄 30 | 31 | [Comprehensive list of all Live Templates in Android Studio](https://github.com/keyboardsurfer/idea-live-templates) 32 | 33 | 34 | ## Postfix code completion in Android Studio 35 | 36 | Android Studio/IntelliJ havea special kind of code completion which allows you to write code specific to a field 37 | 38 | - `.null` will auto complete to `if( == null)` 39 | - `.notnull` will auto complete to `if( != null)` 40 | - `.var` will auto complete to `T name = ` 41 | - `.field` will auto complete to create a global field variable `field = ` 42 | - `.for` will auto complete to `for(T item : )` 43 | - `.fori` will auto complete to 44 | 45 | `for(int i = 0; i < .length; i++)` 46 | - `.forr` will auto complete to 47 | 48 | `for(int i = .length - 1; i > 0 ; i--)` 49 | 50 | Complete list of available postfix code completion can be found via navigating inside Android Studio/IntelliJ menu: 51 | 52 | **Settings → Editor → Postfix Templates** 53 | -------------------------------------------------------------------------------- /src/use-plugins-in-as.md: -------------------------------------------------------------------------------- 1 | # Use plugins to become more efficient 2 | 3 | 1. [KeyPromoter X](https://plugins.jetbrains.com/plugin/9792-key-promoter-x) 4 | 5 | The plugin basically will annoy the hell out of you by showing you a big screen overlay with the key combination you should have used, if you used your mouse to execute some command to a level when you basically would start using the key combination just to avoid KeyPromoter annoying you all the time. It also has some useful features, like it will prompt you to create a key binding for a command whenever an action does not have a key binding and you have used it 3 times using your cursor. [ Old Version: [KeyPromoter](https://plugins.jetbrains.com/plugin/4455)] 6 | 7 | 2. [String Manipulation](https://plugins.jetbrains.com/plugin/2162) 8 | 9 | Provides actions for text manipulation such as Toggle case, encode/decode, sorting, 10 | 11 | 3. [Lines Sorter](https://plugins.jetbrains.com/plugin/5919) 12 | 13 | Add Sort Lines action in Edit menu to sort selected lines or whole file if the selection is empty. 14 | 15 | 4. [Findbugs](https://plugins.jetbrains.com/plugin/3847?pr=idea) 16 | 17 | Provides static byte code analysis to look for bugs in Java code from within Android Studio 18 | 19 | 5. [Sonar Lint](https://plugins.jetbrains.com/plugin/7973) 20 | 21 | The plugin that provides on-the-fly feedback to developers on new bugs and quality issues injected into Java, JavaScript and PHP code. 22 | 23 | 6. [Checkstyles](https://plugins.jetbrains.com/plugin/1065) 24 | 25 | The plugin provides both real-time and on-demand scanning of Java files from within Android Studio. 26 | 27 | 7. [ADB Idea](https://plugins.jetbrains.com/plugin/7380) 28 | 29 | The plugin that adds ADB commands to Android Studio and IntelliJ such as ADB Uninstall App, ADB Kill App, ADB Restart App, etc 30 | 31 | 8. [Exynap](https://plugins.jetbrains.com/androidstudio/plugin/8600-exynap) 32 | 33 | The plugin which helps you find and implement the code you require in an instant. 34 | 35 | 9. [Dagger IntelliJ Plugin](https://github.com/square/dagger-intellij-plugin) 36 | 37 | The Dagger IntelliJ plugin creates visual connections between a @Inject object and the @Provides method that creates it. 38 | 39 | 10. [JVM Debugger Memory View](https://plugins.jetbrains.com/idea/plugin/8537-jvm-debugger-memory-view) 40 | 41 | This plugin extends the built-in JVM debugger with capabilities to explore objects in the JVM heap during a debug session. 42 | 43 | 11. [Android Parcelable code generator](https://plugins.jetbrains.com/plugin/7332-android-parcelable-code-generator) 44 | 45 | Plugin which generates Android Parcelable boilerplate code for you. 46 | -------------------------------------------------------------------------------- /src/working-with-gradle-wrapper.md: -------------------------------------------------------------------------------- 1 | # Working with gradle wrapper 2 | 3 | * **To force re-download of dependencies** 4 | 5 | ```gradle 6 | ./gradlew --refresh-dependencies 7 | ``` 8 | 9 | * **To exclude a certain task from being run by gradle** 10 | 11 | Suppose you want to exclude the task `javaDoc` then use `-x` option followed by the task name, i.e `javaDoc` in this case. 12 | 13 | ```gradle 14 | ./gradlew clean build -x javaDoc 15 | ``` 16 | * **Stop a running gradle build process** 17 | 18 | ```bash 19 | ./gradlew -stop 20 | ``` 21 | 22 | * **Upgrade gradle wrapper to latest release version i.e 6.5** 23 | 24 | Run this inside your project folder via terminal 25 | 26 | ```bash 27 | ./gradlew wrapper --gradle-version 6.5 --distribution-type all 28 | ``` 29 | 30 | * **Make use of Build Cache to speed up your builds.** 31 | 32 | Set the below property in your global `gradle.properties` file 33 | 34 | ``` 35 | android.enableBuildCache=true 36 | ``` 37 | 38 | * **Make your builds faster by building offline** [[Ref Link]](https://medium.com/@cesarmcferreira/mastering-the-terminal-side-of-android-development-e7520466c521#.1cw4bto7f) 39 | 40 | > The `--offline` flag tells gradle to always use dependency modules from the cache, regardless if they are due to be checked again. When running offline, gradle will never attempt to access the network to perform dependency resolution. If required modules are not present in the dependency cache, build execution will fail. 41 | 42 | - Assembling develop debug at full speed: 43 | 44 | ```gradle 45 | ./gradlew assembleDevelopDebug --offline 46 | ``` 47 | 48 | - Running your unit tests at full speed: 49 | 50 | ```gradle 51 | ./gradlew test --offline 52 | ``` 53 | 54 | * Run a single unit test from the command line using the `--tests` option e.g: `./gradlew testDebugUnitTest --tests "*.MainPresenterTest"` . Use `*` to avoid typing the entire package name. [[Ref Link](https://twitter.com/molsjeroen/status/976469806068256769)] 55 | 56 | --------------------------------------------------------------------------------