【转】Android Application Development: 10 Tips for More Efficient Apps

The best recipe for becoming a complete flop in Google Play is to release an app that is battery and memory hungry with a slow interface. Most likely, these qualities will ensure negative reviews from users and result in a bad reputation, even if your app has great designand a unique idea.

Every drawback in product efficiency, battery and memory consumption can really affect your app’s success. That’s why it is critical to develop well-optimized, smooth running apps that never make Android system guard against them. We will not speak about efficient coding, since it goes without saying that the code you write should stand any performance test. But even brilliant code takes time to run. In today’s post, we’ll talk about how to minimize this time and make Android apps that users love.

Efficient threading

Tip 1. How to off-load operations onto threads in background

Since by default all operations in an app run on the main thread (UI thread) in the foreground, the app responsiveness might be affected, which will imminently result in hangs, freezes and even system errors.

To reinforce responsiveness, you should shift long-running tasks (e.g. network or database operations, complex calculations) from an app‘s main thread to a separate background thread. The most effective way to accomplish this task is at a class level. You can use AsyncTask class or IntentService class to organize background work. Once you have implemented an IntentService, it starts when needed and handles requests (Intents) using a worker thread.

When using IntentService, you should consider the following limitations:

  • This class does not put results to UI, so to show results to users use Activity.
  • Only one request is processed at a time.
  • Any request processing can not be interrupted.

Tip 2. How to avoid ANR and stay responsive

The same approach of off-loading long-running operations from the UI thread will save your users from the "Application Not Responding" (ANR) dialog. What you need to do is to create a background worker thread by extending AsyncTask and implementing doInBackground() method.

Another option is to create a Thread or HandlerThread class of your own. Keep in mind that unless you specify "background" priority for the thread, it will slow down the app since the default thread priority is the same as of the UI thread.

Tip 3. How to initiate queries on separate threads

Displaying data is not immediate, although you can fasten it by using CursorLoader objects, which allows not to distract Activity from interacting with a user while query is processing in the background.

Armed with this object your app would initiate a separate background thread for each ContentProvider query and return results to Activity from which the query was called only when the query is finished.

Tip 4. What else you can do

  • Use StrictMode to detect potentially lengthy operations you do in the UI thread.
  • Use special tools, i.g. Systrace, Traceview, to find bottlenecks in your app responsiveness.
  • Show progress to users with a progress bar.
  • Display splash screens if initial setup is time-consuming.

Device battery life optimization

We cannot blame users for angrily uninstalling applications that abuse battery life. The main threats to battery life are:

  • Regular wake-ups for updates
  • Data transfer via EDGE and 3G
  • Textual data parsing, regex without JIT

Tip 5. How to optimize networking issues

  1. Make your app skip operations if there is no connection; update only if 3G or WiFi is connected and there is no roaming.
  2. Choose compact data format, e.g. binary formats that combine text and binary data into one request.
  3. Use efficient parser; consider choosing stream parsers over tree parsers.
  4. For faster UX lessen round-trip times to server.
  5. When possible use framework GZIP libs for text data to make the best use of CPU resources.

Tip 6. How to optimize apps working in foreground

  1. When designing wakelocks, set the lowest level possible.
  2. To avoid battery costs caused by potential bugs you might have missed, use specific timeouts.
  3. Enable android:keepScreenOn.
  4. In addition to GC (garbage collection) consider recycling Java objects manually, e.g. XmlPullParserFactory and BitmapFactory; Matcher.reset(newString) for regex; StringBuilder.setLength(0).
  5. Mind synchronization issues, although it can be safe when driven by UI thread.
  6. Recycling strategies are used heavily in ListView.
  7. Use coarse network location not GPS when possible. Just compare 1mAh for GPS (25 sec. * 140mA) and 0.1mAh for network (2 seconds * 180mA).
  8. Make sure to unregister as GPS location updates can continue even after onPause(). When all applications unregister, users can enable GPS in Settings without blowing the battery budget.
  9. Since the calculation of a floating point requires lots of battery power, you might consider using microdegrees for bulk geo math and caching values when performing DPI tasks with DisplayMetrics.

Tip 7. How to optimize apps working in background

  1. Since each process requires 2MB and might be restarted when foreground apps need memory, make sure the services are short-lived.
  2. Keep memory usage low.
  3. Design app to update every 30 minutes but only if device is already awake.
  4. Services that pall or sleep are bad, that is why you should use AlarmManager or <receiver> manifest elements: stopSelf() when finished. When you start service using AlarmManager, apply the *_WAKEUP flags with caution. Let Android bin your application update together with the rest through setInexactRepeating(). When using <receiver>, enable/disable its components in manifest dynamically, especially when no-ops.

Tip 8. What else you can do

  • Check current states of battery and network before launching a full update; wait for better states for bulk transfers.
  • Provide users with battery usage options, e.g. update intervals and background behavior.

Implementing UI that leaves minimum memory footprints

Tip 9. How to identify layout performance problems

When creating UI sticking solely to basic features of layout managers, you risk to create memory abusing apps with annoying delays in the UI. The first step to implementation of a smooth, memory caring UI is to search your application for potential layout performance bottlenecks with Hierarchy Viewer tool included into Android SDK: <sdk>/tools/.

Another great tool for discovering performance issues is Lint. It scans application sources for possible bugs along with view hierarchy optimizations.

Tip 10. How to fix them

If layout performance results reveal certain drawbacks, you might consider to flatten the layout by converting it from LinearLayout class to RelativeLayout class, lowing level hierarchy.

To perfection and beyond

Even though each tip mentioned above might seem like a rather small improvement, you might see unexpectedly efficient results if these tips become an essential part of your daily coding. Let Google Play see more brilliant apps that work smoothly, quickly, and consume less battery power, bringing the Android world one more step closer to perfection.

时间: 2024-10-09 22:20:52

【转】Android Application Development: 10 Tips for More Efficient Apps的相关文章

; AutoHotkey全自动安装环境设置和测试JAVA+Eclipas+Android+JRE+JDK+SDK+ADT+Android模拟器+Android Virtual Device Manager+NDK+Studio+Doc+Help+Android Application Project编程调试windows环境[草稿版] DetectHiddenWindows,On SetTitl

; AutoHotkey全自动安装环境设置和测试JAVA+Eclipas+Android+JRE+JDK+SDK+ADT+Android模拟器+Android Virtual Device Manager+NDK+Studio+Doc+Help+Android Application Project编程调试windows环境[草稿版] DetectHiddenWindows,OnSetTitleMatchMode,2 ; 激活窗口并单击按钮IfWinExistActiveControlClick

Command Line Android Application Debugging

http://codeseekah.com/2012/02/16/command-line-android-development-debugging/ I personally have a distaste towards IDEs, preferring lightweight solutions, with maybe less convenience. I addition to saving resources and having direct control over what

Android application testing with the Android test framework

目录(?)[-] Android automated testing 1 How to test Android applications Tip 2 Unit tests vs functional tests 3 JUnit 3 4 Running tests on a server without display Test hooks into the Android framework 1 Instrumentation 2 How the Android system executes

Android -- uses-sdk:minSdkVersion 10 cannot be smaller than version L declared in library com.android.support:appcompat-v7:21.0.0-rc1

这是一个报错,是我在Android Studio上添加完Support-v4和v7包之后爆出的错误,百度了好久也没有百度到.当时我的项目有minSdkVersion 19. 设置版本最小为L的时候也会出错,并且我的测试机是4.3,根本就无法安装. defaultConfig { .... minSdkVersion 'L' .... } 解决办法 1.将compileSdkVersion设置成为 compileSdkVersion 'android-L' 这个解决方案只适用于L版本,如果尝试部署

10 Tips for Writing Better Code (阅读理解)

出发点 http://www.tuicool.com/articles/A7VrE33 阅读中文版本<编写质优代码的十个技巧>,对于我编码十年的经验,也有相同感受, 太多的坑趟过,太多的经历走过,对良好编码的技巧,只能说更加心有灵犀. 下面从英文原版阅读,结合自己的理解,尝试注解下作者的观点. 注解 -- 原文见下网址 https://cdiggins.github.io/blog/programming-tips.html 10 Tips for Writing Better Code 注:

初识最简单的android application目录结构

认识android目录结构非常重要.犹如单词对于学习一门语言一样重要一样.在今后学习android 内核源码时候,也是最开始需要先熟悉android源码目录结构一样.刚开始学习目录结构,自然有可能比较枯燥,这可以在后期不断熟悉的时候,进行不断的总结顾名思义(src, source code)该文件夹是放项目的源代码的.打开HelloWorld.java文件会看到如下代码:. 最简单的helloworld应用程序目录结构: 1,src目录: src:source code 该文件夹是放项目的源代码

Oracle Fusion Applications (11.1.8) Media Pack and Oracle Application Development Framework 11g (11.1.1.7.2) for Microsoft Windows x64 (64-bit)

Oracle Fusion Applications (11.1.8) Media Pack for Microsoft Windows x64 (64-bit) 重新搜索   常见问题    提示      查看自述文件可帮助确定需要下载的文件. 请打印包含可下载文件列表的页面.该页面包含部件号列表,以及在安装过程中可能需要参考的相应说明. endv 您好!单击下载按钮即表示您同意使用此门户 上的软件所适用的 Oracle 条款和条件.不是 endv?请勿下载此软件并 使用您的帐户登录.END

WEB Application Development Integrator : 应用设置

1.1.       系统安装 应用 Oracle EBS WEB Application Development Integrator WEB ADI在Oracle EBS 11.5.10.* 版本中,配置不同: WEB ADI在Oracle EBS R12.0.4版本中,默认安装: 职责 在Oracle EBS 11.5.10.2环境中,WEB ADI的职责名:Oracle Web ADI: 在Oracle EBS R12.0.4  环境中,WEB ADI的职责名:Desktop Integ

Gradle build Android application groovy—DSL特定领域语言

前言 现在,搞APP开发居多,编译/打包等问题立即就成痛点了.一个APP有多个版本,Release版.Debug版.Test版.甚至针对不同APP Store都有不同的版本.在以前ROM的环境下,虽然可以配置Android.mk,但是需要依赖整个Android源码,而且还不能完全做到满足条件,很多事情需要手动搞.一个app如果涉及到多个开发者,手动操作必然会带来混乱. library工程我们需要编译成jar包,然后发布给其他开发者使用.以前是用eclipse的export,做一堆选择.要是能自动