Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of optimizing power consumption for Android performance

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article Xiaobian for you to introduce in detail "what is the method of Android performance optimization of electricity", the content is detailed, the steps are clear, the details are handled properly, I hope this article "what is the method of Android performance optimization of electricity" can help you solve your doubts, the following follows the editor's ideas slowly in depth, together to learn new knowledge.

1) Understanding Battery Drain

The power consumption of each hardware module of the mobile phone is different, some modules are very power-consuming, while some modules are relatively much less power consumption.

The calculation and statistics of electricity consumption is a troublesome and contradictory thing, and recording electricity consumption itself is also a matter of electricity consumption. The only viable option is to use a third-party device to monitor electricity so that the real power consumption can be obtained.

When the device is on standby, the power consumption is very small. Take the N5 as an example, if you turn on the flight mode, you can stand by for nearly a month. But when the screen is lit, each module of the hardware needs to start working, which consumes a lot of power.

After using a WakeLock or JobScheduler wake-up device to handle scheduled tasks, be sure to get the device back to its original state in a timely manner. Each time the cellular signal is awakened for data transmission, it consumes a lot of power, which consumes more power than operations such as WiFi.

2) Battery Historian

Battery Historian is a new API introduced by Android 5.0. The power consumption information on the device can be obtained through the following instructions:

$adb shell dumpsys batterystats > xxx.txt / / get the power consumption information of the whole device $adb shell dumpsys batterystats > com.package.name > xxx.txt / / get the power consumption information related to the specified app

Once we have the raw power consumption data, we need to convert the data information into a more readable html file through a python script written by Google:

$python historian.py xxx.txt > xxx.html

Open the converted html file and you can see the list data generated by TraceView. There is a lot of data information here, so we won't expand it here.

3) Track Battery Status & Battery Manager

We can get the current charging status of the phone by using the following code:

/ / It is very easy to subscribe to changes to the battery state, but you can get the current / / state by simply passing null in as your receiver. Nifty, isn't that? IntentFilter filter = new IntentFilter (Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.registerReceiver (null, filter); int chargePlug = batteryStatus.getIntExtra (BatteryManager.EXTRA_PLUGGED,-1); boolean acCharge = (chargePlug = = BatteryManager.BATTERY_PLUGGED_AC); if (acCharge) {Log.v (LOG_TAG, "The phone is charging!");}

The above example demonstrates how to get the charging status of the phone immediately, and after getting the charging status information, we can optimize some of the code. For example, we can judge that some very power-consuming operations are performed only when the phone is currently charging for AC.

/ * * This method checks for power by comparing the current battery state against all possible * plugged in states. In this case, a device may be considered plugged in either by USB, AC, or * wireless charge. (Wireless charge was introduced in API Level 17.) * / private boolean checkForPower () {/ / It is very easy to subscribe to changes to the battery state, but you can get the current / / state by simply passing null in as your receiver. Nifty, isn't that? IntentFilter filter = new IntentFilter (Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = this.registerReceiver (null, filter); / / There are currently three ways a device can be plugged in. We should check them all. Int chargePlug = batteryStatus.getIntExtra (BatteryManager.EXTRA_PLUGGED,-1); boolean usbCharge = (chargePlug = = BatteryManager.BATTERY_PLUGGED_USB); boolean acCharge = (chargePlug = = BatteryManager.BATTERY_PLUGGED_AC); boolean wirelessCharge = false; if (Build.VERSION.SDK_INT > = Build.VERSION_CODES.JELLY_BEAN_MR1) {wirelessCharge = (chargePlug = = BatteryManager.BATTERY_PLUGGED_WIRELESS);} return (usbCharge | | acCharge | | wirelessCharge);}

4) Wakelock and Battery Drain

It is a contradictory choice between keeping more power efficiently and constantly prompting users to use your App. But we can use some better ways to balance the two.

Suppose your phone is loaded with a large number of social apps, even if the phone is on standby, it will often be awakened by these apps to check for synchronized new data information. Android will constantly turn off all kinds of hardware to extend the standby time of the phone, first the screen will gradually dim until it is turned off, and then CPU will go to sleep, all to save valuable power resources. But even in this state of sleep, most apps will try to work, and they will keep waking up the phone. One of the easiest ways to wake up a phone is to use PowerManager.WakeLock 's API to keep CPU working and prevent the screen from dimming off. This allows the phone to be awakened, perform work, and then go back to sleep. It's easy to know how to get WakeLock, but it's also important to release WakeLock in time, and improper use of WakeLock can lead to serious errors. For example, the return time of the data requested by the network is uncertain, resulting in an hour of waiting for things that would have taken only 10 seconds, which will lead to a waste of electricity. This is why it is critical to use the wakelock.acquice () method with a timeout parameter.

But setting a timeout alone is not enough to solve the problem, for example, how long a timeout is appropriate? When will you try again and so on? The correct way to solve the above problems may be to use imprecise timers. Usually, we set a time to do something, but it might be better to change the time dynamically. For example, if there is another program that needs to wake up 5 minutes later than the time you set, * can wait until then when two tasks are bundled together at the same time, which is the core working principle of imprecise timers. We can customize the scheduled task, but if the system detects a better time, it can delay your task to save power consumption.

This is exactly what JobScheduler API does. It will combine the ideal wake-up time according to the current situation and tasks, such as when charging or connecting to the WiFi, or centralizing tasks together. We can implement many free scheduling algorithms through this API.

5) Network and Battery Drain

The following content comes from the efficient download section of the official Training document on the power consumption of cellular signals on mobile phones (Radio).

In general, there are three states of power consumption when data is transmitted over a 3G mobile network:

Full power: the state of energy in which a mobile network connection is activated, allowing the device to operate at a transmission rate of *.

Low power: an intermediate state that consumes about 50% of the power consumed in the Full power state.

Standby: * status, no data connection needs to be transmitted, and the power consumption is the least.

The following figure is a typical diagram of 3G Radio State Machine.

In short, in order to reduce power consumption, in the cellular mobile network, * * can execute network requests in batches and try to avoid frequent interval network requests.

Through the Battery Historian we learned earlier, we can get the power consumption data of the device. If the mobile cellular network (Mobile Radio) power consumption in the data shows the following situation, the interval is very small, and it appears frequently and intermittently, which means the power consumption performance is very poor:

After optimization, if the following diagram is presented, the performance of power consumption is good:

In addition, under the WiFi connection, the power consumption of the network transmission is much less than that of the mobile network, so the data transmission under the mobile network should be reduced as much as possible, and the data should be transmitted more in the WiFi environment.

So how can tasks be cached and executed in batches? Next, it's Job Scheduler's turn.

6) Using Job Scheduler

With Job Scheduler, what the application needs to do is to determine which tasks are not urgent and can be handled by Job Scheduler. Job Scheduler focuses on the received tasks, selects the right time and the right network, and then executes them together.

The following is a brief example of using Job Scheduler, which requires a JobService first:

Public class MyJobService extends JobService {private static final String LOG_TAG = "MyJobService"; @ Override public void onCreate () {super.onCreate (); Log.i (LOG_TAG, "MyJobService created");} @ Override public void onDestroy () {super.onDestroy (); Log.i (LOG_TAG, "MyJobService destroyed");} @ Override public boolean onStartJob (JobParameters params) {/ / This is where you would implement all of the logic for your job. Note that this runs / / on the main thread, so you will want to use a separate thread for asynchronous work / / (as we demonstrate below to establish a network connection) / / If you use a separate thread, return true to indicate that you need a "reschedule" to / / return to the job at some point in the future to finish processing the work. Otherwise, / / return false when finished. Log.i (LOG_TAG, Totally and completely working on job + params.getJobId ()); / / First, check the network, and then attempt to connect. If (isNetworkConnected ()) {new SimpleDownloadTask () .execute (params); return true;} else {Log.i (LOG_TAG, "No connection on job" + params.getJobId () + "; sad face");} return false;} @ Override public boolean onStopJob (JobParameters params) {/ / Called if the job must be stopped before jobFinished () has been called. This may / / happen if the requirements are no longer being met, such as the user no longer / / connecting to WiFi, or the device no longer being idle. Use this callback to resolve / / anything that may cause your application to misbehave from the job being halted. / / Return true if the job should be rescheduled based on the retry criteria specified / / when the job was created or return false to drop the job. Regardless of the value / / returned, your job must stop executing. Log.i (LOG_TAG, "Whelp, something changed, so I'm calling it on job" + params.getJobId ()); return false;} / * * Determines if the device is currently online. * / private boolean isNetworkConnected () {ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo (); return (networkInfo! = null & & networkInfo.isConnected ());} / * * Uses AsyncTask to create a task away from the main UI thread. This task creates a * HTTPUrlConnection, and then downloads the contents of the webpage as an InputStream. * The InputStream is then converted to a String, which is logged by the * onPostExecute () method. * / private class SimpleDownloadTask extends AsyncTask {protected JobParameters mJobParam; @ Override protected String doInBackground (JobParameters... Params) {/ / cache system provided job requirements mJobParam = params [0]; try {InputStream is = null; / / Only display the first 50 characters of the retrieved web page content. Int len = 50; URL url = new URL ("https://www.google.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection (); conn.setReadTimeout (10000); / / 10sec conn.setConnectTimeout (15000); / / 15sec conn.setRequestMethod (" GET "); / / Starts the query conn.connect (); int response = conn.getResponseCode (); Log.d (LOG_TAG," The response is: "+ response); is = conn.getInputStream (); / / Convert the input stream to a string Reader reader = null Reader = new InputStreamReader (is, "UTF-8"); char [] buffer = new char [len]; reader.read (buffer); return new String (buffer);} catch (IOException e) {return "Unable to retrieve web page.";}} @ Override protected void onPostExecute (String result) {jobFinished (mJobParam, false); Log.i (LOG_TAG, result);}

Then the simulation triggers N tasks by clicking Button, which is handed over to JobService.

Public class FreeTheWakelockActivity extends ActionBarActivity {public static final String LOG_TAG = "FreeTheWakelockActivity"; TextView mWakeLockMsg; ComponentName mServiceComponent; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_wakelock); mWakeLockMsg = (TextView) findViewById (R.id.wakelock_txt); mServiceComponent = new ComponentName (this, MyJobService.class); Intent startServiceIntent = new Intent (this, MyJobService.class); startService (startServiceIntent); Button theButtonThatWakelocks = (Button) findViewById (R.id.wakelock_poll) TheButtonThatWakelocks.setText (R.string.poll_server_button); theButtonThatWakelocks.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {pollServer ();}});} / * * This method polls the server via the JobScheduler API. By scheduling the job with this API, * your app can be confident it will execute, but without the need for a wake lock. Rather, the * API will take your network jobs and execute them in batch to best take advantage of the * initial network connection cost. * * The JobScheduler API works through a background service. In this sample, we have * a simple service in MyJobService to get you started. The job is scheduled here in * the activity, but the job itself is executed in MyJobService in the startJob () method. For * example, to poll your server, you would create the network connection, send your GET * request, and then process the response all in MyJobService. This allows the JobScheduler API * to invoke your logic without needed to restart your activity. * * For brevity in the sample, we are scheduling the same job several times in quick succession, * but again, try to consider similar tasks occurring over time in your application that can * afford to wait and may benefit from batching. * / public void pollServer () {JobScheduler scheduler = (JobScheduler) getSystemService (Context.JOB_SCHEDULER_SERVICE); for (int iTuno; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report