πŸ“œ ⬆️ ⬇️

Android Tips and Tricks

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


DescriptionMacLinux / Win
Quick search for settings, actions in IDECmd + shift + aCtrl + Shift + A
Override the parent class methodCmd + oCtrl + O
Search file by nameCmd + shift + oCtrl + Shift + N
List of recently edited filesCmd + Shift + ECtrl + Shift + E
List of recently opened filesCmd + eCtrl + E
Last edited fileCmd + shift + backspaceCtrl + Shift + Backspace
Find all the places where the method / variable is used.Opt + F7Alt + F7
As the previous item, only in the popup windowCmd + opt + f7Ctrl + Alt + F7
Matching code to code styleCmd + opt + lCtrl + Alt + L
Surround the code block with a construct (if, else, try)Opt + Cmd + TAlt + Ctrl + T
Open terminalOpt + F12Alt + F12
Generate Setter / Getters /Cmd + nAlt + ins
Class search by nameCMD + OCtrl + N
Name refactoringShift + F6Shift + F6
Quick fixOpt + EnterAlt + Enter
Go to variable declaration, class, methodCmd + bCtrl + B
Show parameter list for methodCmd + pCtrl + P
Refactoring menuCtrl + TCtrl + Alt + Shift + T
Kill the processCmd + f2Ctrl + F2
Search by projectShift + ShiftShift + Shift
Delete rowCmd + backspaceCtrl + Y
Duplicate lineCmd + dCtrl + D
Expand / Reduce SelectionOpt + Up / Down Arrow keyShift + Ctrl + W
Multiline selectionCtrl + GAlt + j
Full list of shortcutsMacosxLinux / Win

Use plugins to increase efficiency.


  1. 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.

  2. String manipulation
    Simplifies working with strings, allows you to sort, translate into other encodings, remove duplicates, trim text and much more.

  3. Lines sorter
    Adds an icon to the menu to sort the selected lines or the whole file if nothing is selected.
    ')
  4. Findbugs
    Static bytecode analyzer to search for bugs in Java code using Android Studio.

  5. Sonar lint
    A plugin that in runtime shows information about new bugs and violations of the quality of code in Java, JavaScript and PHP.

  6. 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.

  7. 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


TemplateDescription
newInstanceGenerates a static method `newInstance` inside Fragment
ToastGenerates Toast.makeText (context, "", Toast.LENGTH_SHORT) .show ();
fbcfindViewById with custom to the desired type of View
constDefine an int constant
logdGenerates Log.d (TAG, "");
logmLog the current method name and its arguments.
logrLog the result of the current method.
logtStatic string TAG for log, with current class name
psfpublic static final
soutPrint a string in System.out
soutmPrints the class name and method name in System.out
soutpPrints the arguments and method values ​​in System.out
visibleSet the visibility of the View to VISIBLE
goneSet the visibility of View GONE
noInstancePrivate constructor with no arguments to prevent the creation of entities

β†’ Full list of Live Templates in Android Studio

Postfix 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.
TemplateDescription
 <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 Codestyle

Use the built-in terminal in Android Studio


Use 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 SDK

Vysor


This 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.

DeskDock


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


  1. Use OkHttp instead of HttpUrlConnect.

    HttpUrlConnect contains a certain number of bugs . Okhttp quite nicely solved them. Announcement Okhttp .
  2. Refer to the local `aar` files as follows .

     dependencies { compile(name:'nameOfYourAARFileWithoutExtension', ext:'aar') } repositories { flatDir { dirs 'libs' } } 

  3. Use Pidcat for more convenient logging.
  4. Use Version Control System (VCS), preferably git
  5. 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.
  6. Use Stetho
    Allows you to debug your applications using Chrome Dev Tools. Includes network monitoring (Network Monitor), displaying Shared Preferences.
  7. Use Battery Historian
    The program for the analysis of battery consumption
  8. 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.
  9. Use Handler instead of TimerTask
  10. Do not use your personal personal email to publish applications.
  11. Use vectors instead of PNG
    If you still have a png, squeeze them. Check out [TinyPNG] (https://tinypng.com) for this.
  12. Use proguard

     android { ... buildTypes { release { minifyEnabled true proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } 

  13. Use shrinkResources

     android { ... buildTypes { release { shrinkResources true minifyEnabled true ... } } } 

  14. To simulate the killing of your application by the system in the background , run in the terminal

     adb shell am kill 

  15. Learn the settings to speed up the build of gradle

     Gradle memory >= Dex memory + 1Gb 

  16. 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 } } 

  17. Learn how to build an application architecture, such as MVP or Clean Architecture
  18. Try to understand and use the TDD principle (Test Driven Development)
  19. Make gradle reload cached dependencies

     ./gradlew --refresh-dependencies 

  20. 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 

  21. More various gradle tricks
  22. Follow the DRY (Do not Repeat Yourself) principle.
  23. Separate packages by features, not by layers.
  24. 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
  25. Use a different package name to debug builds.

     android { buildTypes { debug { applicationIdSuffix '.debug' versionNameSuffix '-DEBUG' } release { // ... } } } 

  26. Check for and fix memory leaks in your android application.
  27. Use the standard name for your resources.
  28. 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 .
  29. Use the appropriate .gitignore in your Android projects, for example, this
  30. Use LeakCanary to detect memory leaks in your application.
  31. 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 

  32. Stop the application build process with gradle

     ./gradlew -stop 

  33. 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.
  34. Do not connect jcenter () and mavenCentral () at the same time in your build.gradle file, because
    JCenter includes MavenCentral .
  35. 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.
  36. 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.
    AliasUsing
     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 

  37. 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.
  38. Use `adb install -g` to grant all permissions listed in the manifest .
  39. 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.
  40. Use Dryrun to quickly and conveniently test a library or sample application.

     dryrun $REMOTE_GIT_URL$ 

  41. Display unit test results directly to the console .

     android { ... testOptions.unitTests.all { testLogging { events 'passed', 'skipped', 'failed', 'standardOut', 'standardError' outputs.upToDateWhen { false } showStandardStreams = true } } } 

  42. 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.
  43. Collect debug builds as soon as possible:

     ./gradlew assembleDevelopDebug --offline 

  44. Run unit tests as fast as possible:

     ./gradlew test --offline 

  45. Encapsulate the Logger in a separate class.
  46. 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.


Source: https://habr.com/ru/post/319562/


All Articles