How to make your code more efficient in Android development
Recently watched a video called doing more with Less:being a good Android citizen, mainly about how to use a few lines of code to improve the performance of Android apps. In this video, the presenter uses an image app as an example of how to apply what's available in Android to improve app performance issues.
The code for this image app: Https://github.com/penkzhou/iogallery. Ppt:http://greenrobot.qiniudn.com/103.pdf.
Now I'll record the contents of the video as follows:
use LRUCache to avoid oom
First of all, our image app is used to display images stored in the phone. When we need to show a lot of images in the app, we need to load these images from disk into memory. If we slide the activity back and forth, the system repeats many disk I/O, and loading multiple images in one activity will consume a lot of memory, causing system memory to become strained and thus affect the user experience.
How to use LRUCache
At this point we can introduce LRUCache to cache the most commonly used images in memory, which avoids a lot of duplicate disk I/O, and allows the app to load no more than the set value when loading images. The specific code is as follows:
This assumes that the ID of the picture (Long) is used as key to obtain the corresponding Bitmappublic class Picturecache extends Lrucache<long, bitmap>{// Sets the maximum byte value, which means that the entire cache can occupy the maximum memory public picturecache (int maxbytesizes) {super (maxbytesizes);} Each time you add Bitmap, the number added to the cache is the default number,//This is because the add is Bitmap, so each add is calculated Bitmap corresponding byte number protected int sizeOf (Long key,bitmap Value) {return Value.getbytecount ();} public void put (long key, Bitmap value);p ublic Bitmap get (Long key);}
How to determine the cache size
Generally we determine the size of the cache by Activitymanager.getmemorysize (). Activitymanager.getmemorysize () indicates the limit of the memory that an app occupies when the system is running properly. So we can use it as a measure of the cache size, for example, in the code below, we use half of it as the cache size:
Final Activitymanager am = (activitymanager) getsystemservice (context.activity_service); final int memoryclassbytes = Am.getmemoryclass () * 1024 * 1024; Picturecache Mcache = new Picturecache (MEMORYCLASSBYTES/2);
the app went backstage.
After we have browsed through the images with this image app, we go back to the Android main screen and start playing the game. As we all know, the game consumes memory. Perhaps we are playing the process, the use of the rest of the available memory is not enough, how to do? Android will kill some background apps at this time to get the appropriate memory.
You need to say a command here first. How do we get the memory footprint of an app? Very simple, use the "adb shell procrank" command line. This command line shows the memory size of all the processes running on the system, typically including VSS, RSS, PSS, USS, where USS is the most important to us, and USS indicates how much of the available memory the system can get from this process if the process is killed by the system.
Okay, back to the previous scene. Android will kill some background programs to supply the memory needed for the game. Assuming that Android has lost the image app because of memory tension, I have played a game and then opened the image app. This time the picture app re-layout, reload the picture, the whole experience is very bad for the user. Is there any way for Android to notify the app before the kill app so that the app is ready?
At this time we will use the ComponentCallbacks2, the details of the document. The app will have a corresponding callback when the system is in a different memory environment, we just need to rewrite the Ontrimmemory method in the activity, the sample code is as follows:
public void Ontrimmemory (int.) {super.ontrimmemory (level), if (level >= trim_memory_moderate) {//60//the app has entered Station for some time, basically means the user next//will not reopen the app, we can clear out all the memory log.v (TAG, "evicting entire thumbnail cache"); Mcache.evictall ();} else if (level >= trim_memory_background) {///40//means that the app has just entered the background, we can reduce the amount of memory occupied by a portion of the cache//to ensure the memory needs of other foreground apps log.v (TAG, "evicting O Ldest half of thumbnail cache "); Mcache.trimtosize (Mcache.size ()/2);}}
This callback is only a recommendation and is not necessarily called by the system. The system may kill the app directly without calling the callback when the memory is tight. But if these callback can be called, this will greatly enhance the user experience of our app.
use Android to bring your own containers
Now we need to add some new features to this app, we want to make this app available for collection (add a property for the image to be a favorite). We will collect multiple images at once, so we can use the GridView multi-select mode. In common sense, we can use HashMap () <long, boolean> to store which photos need to be collected. However, the use of hashmap here is a bit overqualified, not high efficiency. We can use Android-specific containers such as sparsebooleanarray to replace HashMap, saving system overhead (mainly the overhead of autoboxing)
read-write operation optimization in SQLite
After we have obtained the image information to be collected (saved in Sparsebooleanarray), we need to say that this data is stored in SQLite, the sample code is as follows:
Sqlitedatabase db;long[] Mphotoids; Contentvalues values = new Contentvalues (); for (long Photoid:mphotoids) {values.put (column_id, photoid); Values.put ( Column_favorite, favorite);d B.insert (table_favorite, null, values);}
In the above code, each insert has overhead. We can consider using transaction at this time. The code is as follows:
Sqlitedatabase db;long[] Mphotoids; Contentvalues values = new Contentvalues ();d b.begintransaction (); Try{for (long Photoid:mphotoids) {Values.put (COLUMN_ ID, photoid); Values.put (Column_favorite, favorite);d B.insert (table_favorite, null, values);} Db.settransactionsuccessful ();} Finally{db.endtransaction ();}
But with this transaction, the DB will be locked, and the more important operation can only wait. What happens when you encounter this situation? Using db.yieldifcontendedsafely, this method means that I am now doing my database operations more than once, and if I run into other database operations, I'll let the other operations finish before I perform my operation. The specific code is as follows:
Sqlitedatabase db;long[] Mphotoids; Contentvalues values = new Contentvalues ();d b.begintransaction (); Try{for (long Photoid:mphotoids) {Values.put (COLUMN_ ID, photoid); Values.put (Column_favorite, favorite);d B.insert (table_favorite, null, values); Db.yieldifcontendedsafely ();} Db.settransactionsuccessful ();} Finally{db.endtransaction ();}
Use broadcast
If we need to add a filter effect to a user's new photos by default, how do we do that? Very good, because Android in API14 when the addition of a new broadcast Intent, called "Android.hardware.action.NEW_PICTURE", that is, when the system added photos, We can intercept this intent. Then we will be in the corresponding broadcastreceiver inside the processing, the relevant code is as follows:
public void OnReceive (context context, Intent Intent) {if (isautoapplyenabled) {//performs the corresponding filter operation final Intent serviceintent = n EW Intent (context, effectservice.class); Serviceintent.setdata (Intent.getdata ()); Context.startservice ( serviceintent);} else {log.d (TAG, "Processed no-op broadcast!");}}
The isautoapplyenabled variable above indicates whether the system is turned on to automatically filter new photos. What if you turn off the default filter feature and set the isautoapplyenabled value to false? The result is that each new photo will have intent come over, but in the OnReceive method does not do the operation. The result is that each time the intent will be transmitted by the system, just walk the different branches, the system still consumes resources.
Therefore, the better solution is that the value of the isautoapplyenabled variable in the system changes, we need to broadcastreceiver to open and close operations accordingly. The packagemanage.setcomponentenabledsetting () method needs to be used specifically.
the last few words
This article is a picture app for the background of the Android development of the official recommended small tip. Knowing this can make your app performance a step further.
All the code involved in this article can be found at: https://github.com/penkzhou/iogallery
How to make your code more efficient in Android development