How to reduce the power consumption of Android applications

Source: Internet
Author: User

If the phone (mobile device) is out of power, can your program still run?

Haha, this is a problem that everyone on Earth knows. How can we reduce the power consumption of Android applications? Today, I once again reviewed the speech by Jeffrey Sharkey at the Google Io Conference (coding for life-battery life, that is ), I also want to share some of my experiences with you.

First, let's take a look at the main usage of Android phones:

 

Obviously, most of the electricity is consumed by network connections, GPS, and sensors.

In short, it consumes a lot of power in the following situations:

1. Transmission of large data volumes.

2. Constantly switch between networks.

3. parse a large amount of text data.

So how can we improve our program?

 

1. In the program that requires network connection, first check whether the network connection is normal. If there is no network connection, you do not need to execute the corresponding program.

To check the network connection, follow these steps:

01 ConnectivityManager mConnectivity;
02 TelephonyManager mTelephony;
03  ……
04 // Check the network connection. If no network is available, no network connection is required.
05 NetworkInfo info = mConnectivity.getActiveNetworkInfo();
06 if (info == null ||
07         !mConnectivity.getBackgroundDataSetting()) {
08         return false;
09 }
10 // Determine the network connection type. Only data in 3G or WiFi is updated.
11 int netType = info.getType();
12 int netSubtype = info.getSubtype();
13 if (netType == ConnectivityManager.TYPE_WIFI) {
14     return info.isConnected();
15 else if (netType == ConnectivityManager.TYPE_MOBILE
16         && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
17         && !mTelephony.isNetworkRoaming()) {
18     return info.isConnected();
19 else {
20     return false;
21 }

2. Use highly efficient data formats and resolution methods. Tests show that the current mainstream data formats use tree-like parsing (such as Dom) and stream-like parsing (SAX), as shown in:

 

Obviously, stream-based Parsing is more efficient, Because Dom Parsing is organized based on the node level after reading the entire document. The stream is used to read and parse data. After the data is read, the parsing is complete.

In terms of data format, JSON and protobuf are much more efficient than XML. xml and JSON are familiar to everyone. protobuf was proposed by Google, A Method of serializing structured data for communication protocols and data storage with language-independent, platform-independent, and good scalability. If you are interested, go to the official website to view more information: http://code.google.com/p/protobuf /.

From the figure above, we can draw a conclusion that we try to parse the data by reading and parsing the same side of sax. for mobile devices, it is best to use lightweight data formats such as JSON.

3. Currently, most websites support gzip compression. Therefore, when downloading large amounts of data, try to use gzip. The usage is as follows:

1 import java.util.zip.GZIPInputStream;
2 HttpGet request =
3     new HttpGet("http://example.com/gzipcontent");
4 HttpResponse resp =
5     new DefaultHttpClient().execute(request);
6 HttpEntity entity = response.getEntity();
7 InputStream compressed = entity.getContent();
8 InputStream rawData = new GZIPInputStream(compressed);

Downloading data using gzip compression can reduce network traffic. You can use gzip to obtain the RSS comparison of 1800 topics.

 

4. Other optimization methods:

Java objects are recycled, especially large Java objects.

Xmlpullparserfactory and bitmapfactory

Matcher. Reset (newstring) for RegEx

Stringbuilder. sentlength (0)

If the positioning requirement is not too high, try not to use GPS positioning. WiFi and mobile network cell may be used for positioning. GPS Positioning consumes much more power than mobile network positioning.

Do not use floating point operations.

The cache technology can be used to obtain screen size and other information without multiple requests.

Many people develop a program that uses a service to constantly update data on the server and sleep the service without updating data. This method consumes a lot of power. Generally, we can use alarmmanager to regularly start the service. As shown in the following figure, the task is executed once every 30th minutes.

1 AlarmManager am = (AlarmManager)
2         context.getSystemService(Context.ALARM_SERVICE);
3 Intent intent = new Intent(context, MyService.class);
4 PendingIntent pendingIntent =
5         PendingIntent.getService(context, 0, intent, 0);
6 long interval = DateUtils.MINUTE_IN_MILLIS * 30;
7 long firstWake = System.currentTimeMillis() + interval;
8 am.setRepeating(AlarmManager.RTC,firstWake, interval, pendingIntent);

The last trick is to check the power before running your program. If the power consumption is too low, you will be prompted to charge your application. Haha! Usage:

View Source Code

Print?

01 public void onCreate() {
02     // Register for sticky broadcast and send default
03     registerReceiver(mReceiver, mFilter);
04     mHandler.sendEmptyMessageDelayed(MSG_BATT, 1000);
05 }
06 IntentFilter mFilter =
07         new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
08 BroadcastReceiver mReceiver = new BroadcastReceiver() {
09     public void onReceive(Context context, Intent intent) {
10         // Found sticky broadcast, so trigger update
11         unregisterReceiver(mReceiver);
12         mHandler.removeMessages(MSG_BATT);
13         mHandler.obtainMessage(MSG_BATT, intent).sendToTarget();
14     }
15 };

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.