- Android Development | Best Practices
- Let’s read about some best practices to be followed while designing and developing Android apps.
- 12 Best Practices For Android Development
- 1. Choose Suitable Development Method
- 2. Maintain High Code Quality
- 3. Always keep a consistent coding style and accurate Architecture
- 4. Learn How To Use Android Documentation
- 5. User Input
- 6. Avoid Deep Level in Layouts
- 7. Keep Design In Mind
- 8. Speeding up Android Gradle Builds
- 9. Go for a selective layout and Re-using layouts with tag
- 10. Using Android Debug Bridge (ADB) for your project
- 11. Handling the Configuration changes of your project/app
- Best practices от Google по разработке Android приложений
- Best practices. UI
Android Development | Best Practices
Let’s read about some best practices to be followed while designing and developing Android apps.
While building your career as an Android developer, there are a few important things that you should always keep in mind, if you want to increase your chances of success. It doesn’t matter if you want to make your own project or work for a recognized company, there are some essential aspects that should never be neglected while developing an app.
Always maintain the code quality. Quality matters a lot. It’s not only about MVP, MVC, MVVM etc., but also about each piece of code, in each part of your app. Here’s a short description for MVVM, MVC, and MVP.
- MVC: Three components — View (your UI), Model (data — that view is displaying) & Controller (contains the logic that alters the model depending on the action triggered by UI).
It’s widely known that MVC is a compound pattern (View and Controller have Strategy Implementation, View itself can be a Composite Implementation and, View and Model are synched through Observer). In this case, Controller doesn’t know anything about View, and the idea is that a View can switch Controllers (for instance, depending upon who has logged to the system) & a single Controller can be used by multiple Views. - MVP: Again three components, but with changed dependencies (look at arrows in the diagram). Over here we replace Controller with Presenter (one which presents the changes done in model back to view). The main difference is that Presenter refers back to the view while Controller doesn’t. Normal pattern found here is to create an abstraction of the View (in terms of properties/ events) & Presenter refers to it.
- MVVM: Model-View-View-Model talks of creating a new model (in addition to your domain model). This model normally adds additional properties from the perspective of View (as we understand that View has controls in addition to data which it’s displaying). For instance, if View had a property IsChecked and Presenter was set in classic MVP, in MVVM Presenter will have that IsChecked Property which View will sync up with. So now a Presenter becomes more like a combination of — View Properties & Model properties which would be synchronized with View. So why not rename Presenter to ViewModel? Do that and you get MVVM.
Always include unit tests. This is the most important part of application development. I recommend running unit tests on JVM, because it’s much faster than running it on an Android device itself or an emulator. If you require any android dependencies, use Robolectric. If you need to mock some objects while testing, use Mockito.
Don’t Use Floating-Point. Floating-point is about 2x slower than integer on Android-powered devices.
Beware of using libraries. Ensure the external libraries you use in application only require needed permissions and do not cause any performance degradation.Think twice before adding any third party library, it’s really a serious commitment.
Get rid of memory leaks with Leak Canary. We’ve all been bitten by memory leaks that cause OutOfMemoryError crashes in our apps at some point, sometimes even in production. Square’s Pierre-Yves Ricau has solved this problem by building LeakCanary, a tool to detect and help fix memory leaks before they ship.
Use Proguard . This will remove all unused code, which will reduce APK size.
Use Android Debug Database . It allows you to view databases and shared preferences directly in your browser.
Perform file and network operations off the UI thread. They take time, and if done on the UI thread can make the app unresponsive, which can lead to “App Not Responding” error. They should always be performed on a worker thread, typically by using an AsyncTask/Loader.
Build apps in record time with Flutter. Flutter is Google’s mobile UI framework for crafting high-quality native interfaces on Android in record time. Flutter works with existing code and is used by developers and organizations around the world. It is free and open source.
Use StringBuffer or Stringbuilder classes when there is a lot of modifications to string of characters.
And keep testing on different OS versions and devices.
Источник
12 Best Practices For Android Development
As Android engineers, we’re all motivated by the desire to create memorable experiences for people all across the world. And, with more people relying on your apps than ever before, expectations are higher, and your job as a designer isn’t getting any easier. Now not only do you have to be updated but also stand unique from other developers to make your unique mark in the market. Listed down are few best practices that you can take on to have better outcomes in your development.
1. Choose Suitable Development Method
Not all apps are built with the same approach. You have to brainstorm, plan and pick an appropriate method before starting the development process. Before proceeding you will have to make a prior move that your further app will be a Native, Hybrid, or Web-based app. There are pros and cons of each of these development methods, having proper research will help you better.
2. Maintain High Code Quality
We all know that Coding is an Art. And once an individual starts coding correctly he/she starts loving the flavor. Moreover how creatively you code, shows how better developer you are. Your Quality Of Code Always Matters. Because writing long code is never a smart step, it not only increases the chances of having more bugs and consumes a lot of time, and creates lots of complexity. Here are few points listed you can adopt for superior code quality.
- To give the finest look to your code you can initially study the code of an expert, analyze their approach and try to modify that.
- Provide the purposes of every function you use.
3. Always keep a consistent coding style and accurate Architecture
- Use descriptive names.
- Always keep your code simple and sober, remove unnecessary lines and keep your work short and descriptive.
Tip: Use Proguard, this will help to remove all unused codes and minimize the APK size.
4. Learn How To Use Android Documentation
Android itself is a very vast concept, and it’s very much impractical to imagine that you are a master in all the concepts and techniques. And when it comes to programming or building application nothing can help you out other than the stack’s documentation. Learning how to use/read and understand the Android Documentation is important this will help you to build lots of applications with a variety of features. So it’s highly recommended to go through developer training at android:- Getting Started | Android Developers
5. User Input
Your project work seems more friendly if it’s highly interacted with the users and it seems more helpful as well. While coding, every text field is planned for a different job. We take input in some text fields as numbers or as alphabets. It is counted as better practice if only the number pad is open if we ask the user for numeric value. The syntax will be:
Other than that if your field is for the password, then it must show a password hint to, easily remember the password. It can be achieved as.
6. Avoid Deep Level in Layouts
Having deep hierarchical code views actually makes the UI slower to manage the layout. Deep hierarchies can mostly be avoided by using the correct view group. It’s a recommendation to use a single-level hierarchy.
7. Keep Design In Mind
The duties of Developers are different that from Designers. For the maximum part, builders tend to be great with technical concepts, whilst designers have recognition for being greater creative. But with that said, you can’t have your blinders on while you’re growing an app. You want to apprehend how the layout additives are going to create so that you can code the app accordingly. To get designers and developers operating collectively and effectively, your whole group desires to be on the identical page. You can use mood boards and lots of other tools to have a thought and maintain the tracking of the design elements organized. This will make your improvement manner plenty less difficult and decrease the possibilities of getting to make masses of modifications overdue in the sport on the way to accommodate the designers. For the ones of you that recognize a way to expand and layout, you should still sort out your design elements in these early stages.
8. Speeding up Android Gradle Builds
- Always keep your Gradle updated and use the latest Gradle plugin for android.
- Enable Offline mode, Gradle Daemon, and Parallel build of your project. to use Gradle offline see the setting done below.
Check the Offline work checkbox. Click Apply or OK.
- Use specific dependency versions instead of Dynamics versions.
- Add below flags in gradle.properties
- org.gradle.jvmargs=-Xmx2048m – Amount of memory allocation increases around 2GB to the Gradle Daemon VM.
- org.gradle.daemon=true – improves the build and allows the data and code to store in memory for the next build.
- org.gradle.configureondemand=true – only project-related tasks are configured, saves time from the Configuration phase of Gradle.
- org.gradle.parallel=true – executes tasks from different projects in parallel. Especially useful for modularising the app.
- android.enableBuildCache=true – speed up build items by sorting files and directories created in previous builds.
- org.gradle.caching=true – Turns on Gradle-caching.
9. Go for a selective layout and Re-using layouts with tag
Be it a website or an app the way of picking a layout before developing your project. But before we choose any layout we need to understand that how the UI of the project is created. So when we talk about layouts as we know there are ConstraintLayout, LinearLayout, RelativeLayout, FrameLayout, CoordinatorLayout, and out of all these layouts, you just need to do performance analysis for some of them before getting started with it. If you have some part of your XML getting reused and you want to Avoid replication of code in different layouts. Just add by extracting them in a separate layout.
10. Using Android Debug Bridge (ADB) for your project
So, ADB is basically a tool that is not only used for reverse engineering but also by a lot of android-tech enthusiasts but very few numbers its total potentials or use it at the fullest and is mostly overlooked. ADB- a command-line tool or we can say a client-server program that lets you communicate with android operating systems. Though developers are not using the features of this tool daily or as quotidian, you can ease your lots of developing experiences. It has lots of features like it can add or remove files/data from your android devices and also address lots hidden of data with just a few clicks on your computer. Developers use these tools for testing and making changes in android OS devices. If a user forgets his mobile password, we can use ADB to delete the password file from the android directory, reboot it and the device is unlocked.
11. Handling the Configuration changes of your project/app
Handling the configuration of the android app is one of the hectic tasks for android developers. Basically what happens in configuration change is the android usually destroys your application’s existing Activities and Fragments and recreates them. Proper handling of the Orientationgives a rich-user experience and makes the app work smooth too. Now you want to listen for simple screen orientation changes programmatically and have your application react to them, you can use the OrientationEventListener class to do this within your Activity. Let’s see its implementation in Activity. Just instantiate an OrientationEventListener and provide its implementation. Following is the example of the Activity class called SimpleOrientationActivity logs orientation information to LogCat:
Источник
Best practices от Google по разработке Android приложений
В данной статье я хотел бы вкратце рассказать про самые последние best practices от Google. Я постарался выделить самые основные моменты, чтобы читатель сразу мог понять, что именно какая-либо фича дает разработчику. Не удивляйтесь, если где-то повторяюсь. Конспектировал + добавлял от себя по ходу просмотров видео в www.youtube.com/channel/UCVHFbqXqoYvEWM1Ddxl0QDg
Также к каждому пункту приводятся все необходимые ссылки для более подробного ознакомления с конкретной best practice.
Best practices. UI
1. Использование hardware accelaration. Позволяет улучшить плавность ui, анимации за счет предарительной отрисовки и хранения этих отрисовок в памяти (вместо динамической постоянной отрисовки и перерисовки)
2. Для кастомных View или анимаций (прозрачность и прочее), рекомендуется использовать hardware accelaration. Пример:
3. В кастомной view, если метод переопределить метод hasOverlappingRendering и возвращать false, то view нельзя будет задавать альфу прочее, зато производительность в раза два поднимется.
4. В onDraw не рекомендуется создавать объекты (типа Paint и т.д.). Данные объекты можно сделать статическими — это экономия памяти + предварительное создание + отсутствие постоянного вызова gc.
Ссылка: www.youtube.com/watch?v=HAK5acHQ53E&index=10&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE
5. Tools: Strict mode. Данная тулза настраивается в настройках разработчика на устройстве. Она позволяет отловить все потенциально узкие места в UI (что-то тормозит, где-то блокируется UI — ThreadPolicy). Также можно отловить memoty leaks (VMPolicy). Настроить режим для приложения можно через соответствующий класс — developer.android.com/reference/android/os/StrictMode.html
6. При создании custom view.
View.invalidate() — вызывает перерисовку элемента. Это зло. Если что-то поменялось, то нужно перерисовывать не весь view, а конкретный Rect (если он видим пользователю).
Не рисовать лишнее. Что не видно, то не рисовать. Банально, но часто этим пренебрегают. Canvas.clipRect() в помощь. Также для быстрого определения, что слой не видим — Canvas.quickReject(. )
Не перегружать слишком в угоду другому CPU и GPU.
7. Bitmap. Желательно подгружать предварительно сжатые картинки с помощью BitmapFactory.Options
developer.android.com/training/displaying-bitmaps/load-bitmap.html
8. Bitmap. При создании Bitmap из картинки (jpeg, png) по умолчанию используется формат ARGB_8888 (32 бита на пиксель). Если критичен вопрос памяти, можно использовать другие форматы (RGB_565 — 16 бит и другие). Выставление данного параметра происходит через BitmapOptions. Конвертация, конечно же, сказывается на производительности.
11. Overdraw. Заставляет GPU работать вхолостую (рисование скрутытх элементов). Для определения overdraw, нужно в DeveloperOptions включить Show GPU Overdraw flag. Также помогает тулза ViewHierarchy.
12. TraceView также хорошо подходит для определения корректности отрисовки. Все отрисовки должны помещаться в 16 мс (60 кадров в секунду).
13. VSYNC. Что это такое.
Refresh rate (60 hz) — это частота обновления экрана, константа. Frame rate — частота обновления фрейма в секунду. Единица измерения GPU.
Обе скорости должны быть синхронизированы для корректного отображения. Для решения данной проблемы используется двойная буферизация. С GPU картинки идут в back buffer, а затем в frame buffer, а оттуда на экран. Между back buffer и frame buffer находится VSYNC, который следит за тем, чтобы данные с back buffer переходили в frame buffer синхронно скорости обновления экрана. Это устраняет возможные коллизии картинки на экране.
Скорость работы GPU (frame rate) должна быть выше скорости обновления экрана (refresh rate) для того, чтобы ui был плавным.
www.youtube.com/watch?v=1iaHxmfZGGc&index=23&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE
14. Tool — Profile GPU Rendering
Подключить можно в DeveloperOptions. Нам интересен граф для приложения. Есть еще для навигации и notification bar. Сам график представляет собой совокупность времен, требуемых на прорисовку frame. График не должен превышать зеленую вертикальную линию — 16ms (скорость обновления экрана).
17. Android UI and the GPU
GPU нужен для растеризации полигонов, текстур. CPU отдает GPU необходимые графические элементы и с помощью OpenGL эти элементы конвертируются в полигоны и текстуры и хранятся в GPU (нужно уточнить?). Плюс другие оптимизации GPU: отрисовка не всего экрана, а изменяемых частей, объединение элементов в полигоны и т.д.:
www.youtube.com/watch?v=WH9AFhgwmDw&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&index=26
18. Show GPU view updates in DevOps — показывает, какие элементы invalidate()
Источник