In this material, you will see various tools and tips that make life easier for Android developers. Most of it is collected directly from familiar developers and contains things that everyone should know. Additions and extensions are welcome, and if you know about some cool mechanism that was not mentioned in the article, do not be lazy to go to the
original and open the pull request.
Know your tools
Android Studio
Do not forget to use shortcuts
Description | Mac | Linux / Win |
Quick search for settings, actions in IDE | Cmd + shift + a | Ctrl + Shift + A |
Override the parent class method | Cmd + o | Ctrl + O |
Search file by name | Cmd + shift + o | Ctrl + Shift + N |
List of recently edited files | Cmd + Shift + E | Ctrl + Shift + E |
List of recently opened files | Cmd + e | Ctrl + E |
Last edited file | Cmd + shift + backspace | Ctrl + Shift + Backspace |
Find all the places where the method / variable is used. | Opt + F7 | Alt + F7 |
As the previous item, only in the popup window | Cmd + opt + f7 | Ctrl + Alt + F7 |
Matching code to code style | Cmd + opt + l | Ctrl + Alt + L |
Surround the code block with a construct (if, else, try) | Opt + Cmd + T | Alt + Ctrl + T |
Open terminal | Opt + F12 | Alt + F12 |
Generate Setter / Getters / | Cmd + n | Alt + ins |
Class search by name | CMD + O | Ctrl + N |
Name refactoring | Shift + F6 | Shift + F6 |
Quick fix | Opt + Enter | Alt + Enter |
Go to variable declaration, class, method | Cmd + b | Ctrl + B |
Show parameter list for method | Cmd + p | Ctrl + P |
Refactoring menu | Ctrl + T | Ctrl + Alt + Shift + T |
Kill the process | Cmd + f2 | Ctrl + F2 |
Search by project | Shift + Shift | Shift + Shift |
Delete row | Cmd + backspace | Ctrl + Y |
Duplicate line | Cmd + d | Ctrl + D |
Expand / Reduce Selection | Opt + Up / Down Arrow key | Shift + Ctrl + W |
Multiline selection | Ctrl + G | Alt + j |
Full list of shortcuts | Macosx | Linux / Win |
Use plugins to increase efficiency.
- KeyPromoter
This plugin will make you suffer by showing a big ugly popup with a key combination that you should use instead of pressing a button in the IDE. After some time you will use shortcuts on the machine, just not to see this terrible popup.
- String manipulation
Simplifies working with strings, allows you to sort, translate into other encodings, remove duplicates, trim text and much more.
- Lines sorter
Adds an icon to the menu to sort the selected lines or the whole file if nothing is selected.
')
- Findbugs
Static bytecode analyzer to search for bugs in Java code using Android Studio.
- Sonar lint
A plugin that in runtime shows information about new bugs and violations of the quality of code in Java, JavaScript and PHP.
- Checkstyle
A plugin that scans Java files using Android Studio and checks them against the settings. It can be integrated into your build system to disable builds with violations.
- Adb idea
A plugin that adds ADB commands (installing and removing an application, restarting an application, etc.) in Android Studio and Intellij.
Use Live Templates when developing in Android Studio
Template | Description |
newInstance | Generates a static method `newInstance` inside Fragment |
Toast | Generates Toast.makeText (context, "", Toast.LENGTH_SHORT) .show (); |
fbc | findViewById with custom to the desired type of View |
const | Define an int constant |
logd | Generates Log.d (TAG, ""); |
logm | Log the current method name and its arguments. |
logr | Log the result of the current method. |
logt | Static string TAG for log, with current class name |
psf | public static final |
sout | Print a string in System.out |
soutm | Prints the class name and method name in System.out |
soutp | Prints the arguments and method values ββin System.out |
visible | Set the visibility of the View to VISIBLE |
gone | Set the visibility of View GONE |
noInstance | Private constructor with no arguments to prevent the creation of entities |
β
Full list of Live Templates in Android StudioPostfix code auto completion in Android Studio
Android Studio / IntelliJ has a special code completion mechanism that allows you to apply a design to a specific variable.
Template | Description |
<expr>.null | null if(<expr> == null) |
<expr>.notnull | null if(<expr> != null) |
<expr>.var | T name = <expr> |
<expr>.field | field = <expr> |
<ArrayExpr>.for | for(T item : <Arrayexpr>) |
<ArrayExpr>.fori | for(int i = 0; i < <Arrayexpr>.length; i++) |
<ArrayExpr>.forr | for(int i = <Arrayexpr>.length - 1; i => 0 ; i--) |
A complete list of available postfix code additions can be found in Settings β Editor β Postfix Templates
Use the Darcula theme in Android Studio
Yes, I realize that this is more a matter of preference. But believe me, using a dark theme will reduce the strain on your eyes.
Do not use uncomfortable / small print.
If possible, try to use a font that is convenient to read and does not cause discomfort for your eyes. I use the
menlo font .
Use codestyle
You should use a standard codestyle. For an example, look at
AOSP Codestyle or
Square IntelliJ CodestyleUse Memory / Network / CPU monitoring in Android Studio to profile your application.
Emulator
In addition to using real devices, you should also use emulators due to the simplicity of their configuration and use. You can also easily adjust the resolution and version of the API for testing.
Genymotion ,
Intel emulator shipped with SDKThis is a very useful tool worthy of special mention. In fact, it allows you to stream the contents of a physical Android device to a laptop screen. It is very convenient when you need to demonstrate a demo of your application at the presentation. We can interact with the real device, and all this will be presented right on the laptop screen. There are free and paid versions, and the paid one is definitely worth buying.
If you need to manipulate a physical Android device (using the keyboard and mouse), then this application will do a great job with this. Allows you to control your Android device as if it were part of a desktop computer.
The free version allows you to use the mouse, the
paid version allows you to use the keyboard and other features. With this application, you can test the application without taking your hands off the laptop keyboard.
Choose the best tools when writing code
- Use OkHttp instead of HttpUrlConnect.
HttpUrlConnect contains a certain number of bugs . Okhttp quite nicely solved them. Announcement Okhttp .
- Refer to the local `aar` files as follows .
dependencies { compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar') } repositories { flatDir { dirs 'libs' } }
- Use Pidcat for more convenient logging.
- Use Version Control System (VCS), preferably git
- Use ClassyShark
A special program for Android developers, with which it allows you to analyze files like .apk, .jar, .class, .dex, .aar, .so. It can show information about the fields and methods of the class, dependencies. Apk, the number of methods used by the application, and so on.
- Use Stetho
Allows you to debug your applications using Chrome Dev Tools. Includes network monitoring (Network Monitor), displaying Shared Preferences.
- Use Battery Historian
The program for the analysis of battery consumption
- When using dependencies, always use constants. For example, "24.2.0"
Avoid using '+' to specify the versions of libraries used.
This will allow you to avoid unexpected bugs or build problems if the new version changes the API. And also it is not necessary during the assembly each time to open an Internet connection to check the latest current version of the dependent library.
- Use Handler instead of TimerTask
- Do not use your personal personal email to publish applications.
- Use vectors instead of PNG
If you still have a png, squeeze them. Check out [TinyPNG] (https://tinypng.com) for this.
- Use proguard
android { ... buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } }
- Use shrinkResources
android { ... buildTypes { release { shrinkResources true minifyEnabled true ... } } }
- To simulate the killing of your application by the system in the background , run in the terminal
adb shell am kill
- Learn the settings to speed up the build of gradle
Gradle memory >= Dex memory + 1Gb
- Separate your .apk using gradle when you use native code. Do not mix everything together, because then you will suffer, understanding the source code.
defaultConfig { ... ndk { abiFilters "armeabi", "armeabi-v7a", "mips", "x86" } } //Split into platform dependent APK splits { abi { enable true reset() include 'armeabi', 'armeabi-v7a', 'mips', 'x86' //select ABIs to build APKs for universalApk false //generate an additional APK that contains all the ABIs } } // map for the version code project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'mips': 5, 'x86': 8] // Rename with proper versioning android.applicationVariants.all { variant -> // assign different version code for each output variant.outputs.each { output -> output.versionCodeOverride = project.ext.versionCodes.get(output.getFilter(com.android.build.OutputFile.ABI), 0) * 1000000 + android.defaultConfig.versionCode } }
- Learn how to build an application architecture, such as MVP or Clean Architecture
- Try to understand and use the TDD principle (Test Driven Development)
- Make gradle reload cached dependencies
./gradlew --refresh-dependencies
- Exclude gradle TASK at assembly. Suppose you want to exclude the 'javaDoc' task, in which case use the '-x' option and name of the task, in this example 'javaDoc'
./gradlew clean build -x javaDoc
- More various gradle tricks
- Follow the DRY (Do not Repeat Yourself) principle.
- Separate packages by features, not by layers.
- Learn how to solve dependency conflicts.
Given the speed of developing android libraries and their updates, at some point you will encounter a dependency conflict in your application. Gradle allows you to solve these problems official documentation
- Use a different package name to debug builds.
android { buildTypes { debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' } release {
- Check for and fix memory leaks in your android application.
- Use the standard name for your resources.
- Start writing gradle tasks yourself
Android uses Gradle as an assembly system, which allows you to simplify a lot of things and write your own tasks for automation. Post on reddit, which contains many useful gradle scripts .
- Use the appropriate .gitignore in your Android projects, for example, this
- Use LeakCanary to detect memory leaks in your application.
- Accelerate gradle build in Android Studio 2.2+
- Go to gradle version 3.1.
Run the following command in your project directory to update the gradle wrapper.
./gradlew wrapper --gradle-version 3.1
- Set the build options in the global in the `gradle.properties` file
android.enableBuildCache=true
- Stop the application build process with gradle
./gradlew -stop
- Configure gradle to automatically download the missing android sdk components.
Set the following option in the global gradle.properties file.
android.builder.sdkDownload=true
This is an experimental option, and it downloads only build tools and platforms, but does not update Google or the Support Repository.
- Do not connect jcenter () and mavenCentral () at the same time in your build.gradle file, because
JCenter includes MavenCentral .
- Clean the gradle cache if you think that the android sdk libraries provided with support and google play services are incompatible.
Go to the ~ / .gradle / caches / directory and delete all the contents in the cache folder.
Open the SDK Manager and resynchronize all the support libraries and google play services.
Next, update the gradle dependencies in the project.
Now everything should be in good condition and work correctly.
- Configure convenient `adb` aliases for your terminal .
Add the following commands to your ~ / .bashrc or ~ / .zshrc file, save and restart the terminal. After that, you can use it as shown in the Usage column.
Alias | Using |
alias screenshot="adb exec-out screencap -p > screen-$(date -j "+%s").png" | screenshot |
alias startintent="adb devices | tail -n +2 | cut -sf 1 | xargs -IX adb -s X shell am start $1" | startintent https://twitter.com/nisrulz |
alias apkinstall="adb devices | tail -n +2 | cut -sf 1 | xargs -IX adb -s X install -r $1" | apkinstall ~/Desktop/DemoApp.apk |
alias rmapp="adb devices | tail -n +2 | cut -sf 1 | xargs -IX adb -s X uninstall $1" | rmapp com.example.demoapp |
alias clearapp="adb devices | tail -n +2 | cut -sf 1 | xargs -IX adb -s X shell pm clear $1" | clearapp com.example.demoapp |
- Set Android Studio to crash when building if the code contains // STOPSHIP .
To enable lint checking for //STOPSHIP
, add to your `build.gradle`
android { ... lintOptions { abortOnError true fatal 'StopShip' } }
If you have //STOPSHIP
comments in the code, the release build will not build. In addition, you can also turn on the highlighting of such comments in Android Studio (disabled by default). Preferences β Editor β Code Style β Inspections
. Look for STOPSHIP in the search and check the box for highlighting.
- Use `adb install -g` to grant all permissions listed in the manifest .
- Use Alfi to search libraries by name. You will be immediately offered a string to include in the gradle application build script. This is essentially a console version of Gradle, please - web applications.
alfi $name_of_library$
Copy the library you want. Paste into your build.gradle.
- Use Dryrun to quickly and conveniently test a library or sample application.
dryrun $REMOTE_GIT_URL$
- Display unit test results directly to the console .
android { ... testOptions.unitTests.all { testLogging { events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' outputs.upToDateWhen { false } showStandardStreams = true } } }
- Build faster using offline mode .
--offline
flag tells gradle to use cache dependencies when building. If you run a build with this flag, gradle will never try to deflate network dependencies. If the required modules are not in the cache, the application will not build.
- Collect debug builds as soon as possible:
./gradlew assembleDevelopDebug --offline
- Run unit tests as fast as possible:
./gradlew test --offline
- Encapsulate the Logger in a separate class.
- If you want to automatically initialize the library, use the Content Provider. Read how Firebase does it .
UI / UX tips
Motion
Material Design uses real-world physics as the basis. Objects in the real world do not move linearly, they move along curved paths and also with acceleration and deceleration, depending on the situation.
Thus, you must manipulate the properties and animate objects so that it looks natural and natural. For example, a car going beyond the screen starts moving slowly, gradually accelerating as it approaches the edge of the screen. Similarly, ui elements must be moved using classes such as AccelerateInterpolator, FastOutSlowInInterpolator, and
others .
Fonts, indents
In principle, non-standard fonts can be used as part of branding, but it is better to stay on standard Roboto and Noto, if possible, especially for the main text because of their recognizability and frequent use.
Roboto covers Latin, Greek and Cyrillic characters, Noto covers
other languages .
Balancing the brightness of the font is one of the most important parameters of modern stylistics. The basic idea is that the smaller the font, the brighter it should be, and vice versa.
The text itself must be aligned on a grid with a 4dp cell.
The ideal text length for large blocks is 40 to 60 characters per line.
Icons
Icons should be 48dp with 1dp edges, which is equivalent to:
48px x 48px - mdpi
72px x 72px - hdpi
96px x 96px - xhdpi
144px x 144px - xxhdpi
192px x 192px - xxxhdpi
An additional icon with a size of 512px x 512px must be provided for Google Play.
The same applies to the icon with a size of 1024px x 500px, which will be displayed in the header on the page of your application.
Ripple
When implementing the Ripple effect, use the
?attr/selectableItemBackground
instead of
?android:attr
,
more . When you implement a Ripple effect on an element like Button,
use :
android:background="?attr/selectableItemBackground"
When implementing a Ripple that goes beyond the edges of the View, such as with an ImageView,
use :
?attr/selectableItemBackgroundBorderless
The remaining items
Items in accordance with Material Design Views should be located on an 8dp mesh grid, if possible. With this approach, the UI
looks structured and enjoyable .
If you need a link to any ViewGroup element (LinearLayout, FrameLayout, RelativeLayout, etc.) and you do not need any specific methods specifically for this type of ViewGroup, then do not store a specific type,
just use the ViewGroup .
Other resources
Bookmark your browser with various popular resources.
Use the free mock API for testing.
All the examples listed below, in one way or another, allow you to test your application without a backend. If you need to use, go through the list and see which of the items best suits your needs and needs in terms of functionality.
Subscribe to digests for android development
More examples of useful programs
As a supplement - Android libraries developed by me personally.