Image caching, gesture and oom analysis of Android development notes _android

Source: Internet
Author: User
Tags anonymous

The three themes of image caching, gestures, and oom are put together because these three issues are often linked in the Android application development process. First, preview large image needs to support gesture scaling, rotation, translation, and other operations; Secondly, the picture needs to be cached locally, avoid frequent access to the network; Finally, the image (Bitmap) is a large memory footprint of the Android, involving HD Big image processing, memory footprint is very large, slightly not cautious, The system will report oom errors.

Thankfully, these three themes are a common problem in Android development, and there are a number of common open source solutions for this. Therefore, this paper mainly explains the author used in the development process of some third-party open Source library. The main contents are as follows:

Comparison and use of 1.Universal Image Loader, Picasso, glide and fresco
Principle and application of 2.PhotoView and Gestureimageview
3.leakcanry Memory Analysis Tool

--------------------------------------------------------------------------------

Comparison and use of universal Image Loader, Picasso, glide and fresco

Universal Image Loader (UIL), Picasso, glide, and fresco are the most common third-party libraries for image loading in Android, which encapsulate memory caching, disk caching, network request caching, thread pooling, etc., and abstract the process of image loading, Greatly avoids the memory overflow caused by loading pictures, and improves the efficiency of picture loading. The following figure is the author recently from the various libraries of the GitHub page to query the information:

What needs to be stated is:

Imageloader is the first open source image caching library, the author has stopped maintenance (11.27);
Picasso's actual author is Square's Jake wharton,android field of absolute Daniel;
Glide is open source by Google employees and is recommended for use in Google I/O 2014 official applications.
fresco pictures are loaded without using Java heap memory, but anonymous shared memory (ASHMEM).

Attach the GitHub address of each library:

Universal Image Loader:https://github.com/nostra13/android-universal-image-loader.git

Picasso:https://github.com/square/picasso.git

Glide:https://github.com/bumptech/glide.git

Fresco:https://github.com/facebook/fresco.git

The basic use of these four picture cache libraries (HelloWorld) can be implemented in a single code, as follows:

UIL:

Imageloader.getinstance (). DisplayImage (URL, imageview);

Picasso:

Picasso.with. Load (URL). into (ImageView);

Glide:

Glide.with. Load (URL). into (ImageView);

Fresco:

Simpledraweeview.setimageuri (URI);

Careful friends can see that Picasso and glide APIs are very similar. In fact, these four libraries are similar in their core ideas of implementation, and can be abstracted into the following five modules:

1.RequestManager, mainly responsible for the request generation and management module;
2.Engine, mainly responsible for creating tasks and executing scheduling;
3.GetDataInterface, get the data interface, mainly used to get the picture data from memory cache, disk cache and network etc.
4.Displayer, mainly used to display pictures, may be imageview encapsulation or other virtual displayer;
5.Processor, mainly responsible for processing pictures, such as image rotation, compression and interception operations.

To say a digression, master the core ideas of the implementation of various open source libraries, you will find that a common feature of software engineering is to improve efficiency by formalizing and abstracting the process. Whether it is the efficiency of the business or the efficiency of development, this may also be the core idea of software as a science.

Design and advantages of Imageloader

The Imageloader loading process is shown below. (Need to declare: The following three flowchart from Trinea, respect the original author copyright)


Imageloader receives the load and displays the picture the task, imageloaderengine the distribution task, obtains the picture data, Bitmapdisplayer displays in the Imageaware.

Imageloader's a bit:

• Support download Progress monitoring
• You can pause the picture load in view scrolling, and you can pause the picture load in the view scrolling through the Pauseonscrolllistener interface.
• The default implementation of a variety of memory caching algorithms, which can be configured to cache the cache algorithm, but imageloader default implementation of a large number of caching algorithms, such as Size maximum first delete, use at least the first deletion, the least recent use, advanced first Delete, the longest time to delete.

• Support for local cache file name rule definitions

Design and advantages of Picasso

The Picasso loading process is as follows:


Picasso receives the load and display picture tasks, the Dispatcher is responsible for distributing and processing, obtains the picture through the MemoryCache and handler, through the picassodrawable displays to target.

Advantages of Picasso:

• With statistical monitoring capabilities, support the use of image caching monitoring, including the cache hit rate, the use of memory size, save the flow, and so on.
• Support priority processing, each task scheduling before the choice of high priority tasks, such as the APP page Banner priority higher than the Icon is very applicable.
• Support delay to picture size calculation complete loading, support flight mode, concurrent thread number depending on network type, mobile phone switch to flight mode or network type conversion will automatically adjust the maximum number of concurrent threads pool, such as WiFi maximum concurrency of 4, 4g for 3,3G 2. Here Picasso determines the maximum concurrency number, rather than the CPU kernel, based on the network type.

• "No" local cache, not to say that there is no local cache, but rather Picasso themselves did not implement, to the Square of another network library okhttp to implement, the advantage is that by requesting Response Header Cache-control and Expire D Control the expiration time of the picture.

Design and advantages of glide

The glide loading process is as follows:


Glide received the load and display resources tasks, Engine processing requests, through the fetcher to obtain data, after transformation processing to target display.

Advantages of Glide:

(1) Image cache-> Media cache
Glide is not only a picture cache, it supports Gif, WebP, thumbnails. Even video, so it's better to be a media cache.

(2) Support priority processing

(3) Consistent with activity/fragment life cycle, support trimmemory
Glide maintains a requestmanager for each context, which is consistent with the activity/fragment lifecycle through Fragmenttransaction, and has a corresponding Trimmemory interface implementation to invoke.

(4) Support Okhttp, volley
Glide By default URLConnection get data, can cooperate with okhttp or volley use. Actual Imageloader, Picasso also support Okhttp, volley.

(5) Memory friendly
The ①glide memory cache has an active design
When fetching data from the memory cache, it is not like a general implementation with get, but with remove, then put the cached data into a activeresources map with a value of soft reference, count the reference number, judge the picture after loading, and recycle if the reference count is empty.

② Memory Cache smaller picture
Glide to the URL, viewwidth, viewheight, screen resolution, etc. as the joint key, the processed picture is cached in the memory cache, rather than the original image to save size

③ is consistent with activity/fragment lifecycle and supports Trimmemory

④ picture defaults to using default RGB565 instead of ARGB888
Although the sharpness is poor, but the picture is smaller, can also be configured to argb_888.

Other: Glide can expire by signature or not using the local cache support URL

About Fresco

Fresco library Open source later, there is no official version 1.0. But its functionality is stronger than the first three libraries, such as:

• Picture storage System anonymous shared memory Ashmem (Anonymous shared Memory) does not allocate Java heap memory, so picture loading does not cause heap memory jitter;
JPEG image Stream loading (first display image contour, then slowly load clear image);
• More perfect image processing, display mode;
JPEG image local (native) transform dimension to avoid oom;
•......

About the system anonymous shared memory Ashmem, which will be detailed in a subsequent article on the use of Android memory, is simply described here:

Inside the Android system, the memory of the Ashmem area does not belong to the Java Heap, nor does it belong to native Heap. When a memory space in the Ashmem is to be released, it is communicated through the system call Unpin. But the data in this memory space is not actually erased. If the Android system finds that memory is tight, it uses the Unpin memory space to store the required data. The memory space that is unpin can be re pin, if this memory space has not been used by others, save the process of re-writing to the ASHMEM data. So, ashmem this principle is a kind of delayed release.

In addition, learn ASHMEM can refer to master Luo Shenyang's blog:

1.Android system Anonymous Shared memory Ashmem (Anonymous shared Memory) Brief introduction and Learning Plan
2.Android system Anonymous Shared memory Ashmem (Anonymous shared Memory) driver source code Analysis
3.Android system Anonymous Shared memory Ashmem (Anonymous shared Memory) principle analysis of sharing between processes

Principle and use of Photoview and Gestureimageview

A typical scenario for using the above Third-party open Source Library to load a picture is to click to view the larger image. Large graphics support gesture scaling, rotation, translation and other operations, imageview gesture scaling, there are many ways, the vast majority of open source custom scaling is modified OnDraw function to achieve. However, the ImageView itself has a scaletype attribute, and scaling can be easily achieved by setting android:scaletype= "Matrix". The advantage of scaling is that it is simple to implement, and there is no flicker in the scaling process because the OnDraw function is not called repeatedly. Also, be aware that ScaleType controls how the image is scaled, which refers to resources rather than backgrounds, in other words, android:src= "@drawable/ic_launcher" rather than android:background= "@ Drawable/ic_launcher ".

A lot of open source implementations can be found on GitHub, which is illustrated in two examples.

Photoview Address: Https://github.com/bm-x/PhotoView.git

Gestureimageview Address: Https://github.com/jasonpolites/gesture-imageview.git

Photoview's introduction:

1.Gradle add dependencies (recommended)

dependencies {
compile ' com.bm.photoview:library:1.3.6 '

(or you can download the project, copy the Info.java and Photoview.java two files to your project, not recommended)--this applies to eclipse.

2.xml add

<com.bm.library.photoview
android:id= "@+id/img"
android:layout_width= "Match_parent"
android: layout_height= "Match_parent"
android:scaletype= "centerinside"
android:src= "@drawable/bitmap1"/> 

3.java Code

 Photoview Photoview = (photoview) Findviewbyid (r.id.img);//Enable picture Scaling feature photoview.enable ();//
Disable the picture scaling feature (default is disabled, as with normal ImageView, the zoom feature needs to be manually invoked enable () enabled) photoview.disenable ();
Get Picture Info Info info = photoview.getinfo ();
From a picture information changes to the present picture, for the picture clicks to enlarge the browsing, the concrete use may refer to the demo use Photoview.animafrom (info); From the current picture changes to the given picture information, used to enlarge the picture and click to reduce to the original position, specific use can refer to the use of the demo Photoview.animato (Info,new Runnable () {@Override public void
Run () {//Animation complete Listener}}); 
Get animation duration int d = photoview.getdefaultanimaduring ();
The basic principle of photoview implementation is to use scaling matrix and gesture monitoring in Photoview inherited from ImageView.  public class Photoview extends ImageView {... private matrix Mbasematrix = new Matrix (); private matrix Manimamatrix = new
Matrix ();
Private Matrix Msynthesismatrix = new Matrix ();
Private Matrix Mtmpmatrix = new Matrix ();
Private Rotategesturedetector Mrotatedetector;
Private Gesturedetector Mdetector;
Private Scalegesturedetector Mscaledetector;
Private Onclicklistener Mclicklistener;
Private ScaleType Mscaletype; ...... } 

The implementation of the Photoview is basically consistent with the above principle, no longer repeat here. For the implementation of the custom control, subsequent articles will be analyzed in detail.

Gestureimageview's profile is as follows:

1.Configured as View in Layout.xml

Code

<linearlayout
xmlns:android= "http://schemas.android.com/apk/res/android"
xmlns:gesture-image= "http ://schemas.polites.com/android "
android:layout_width=" fill_parent "
android:layout_height=" Fill_parent " >
<com.polites.android.gestureimageview
android:id= "@+id/image"
android:layout_width= "Fill_ Parent "
android:layout_height=" wrap_content "
android:src=" @drawable/image "
gesture-image: Min-scale= "0.1"
gesture-image:max-scale= "10.0"
gesture-image:strict= "false"/>

2.Configured programmatically

Code

Import Com.polites.android.GestureImageView;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.ViewGroup;
Import Android.widget.LinearLayout.LayoutParams;
public class Sampleactivity extends activity {
@Override public
void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (r.layout.main);
Layoutparams params = new Layoutparams (layoutparams.wrap_content, layoutparams.wrap_content);
Gestureimageview view = new Gestureimageview (this);
View.setimageresource (r.drawable.image);
View.setlayoutparams (params);
ViewGroup layout = (viewgroup) Findviewbyid (r.id.layout);
Layout.addview (view);
}


The principle is basically consistent with Photoview, no longer repeat.

Iii. oom Analysis Tools--leakcanary

Leakcanary's introduction:

A Memory leak Detection library for Android and Java.

Visible, Leakcanary is mainly used to detect a variety of memory can not be GC, resulting in leakage of the situation.

Leakcanary's address Https://github.com/square/leakcanary.git

Demo Address:

Https://github.com/liaohuqiu/leakcanary-demo.git (AS)

Https://github.com/teffy/LeakcanarySample-Eclipse.git (Eclipse)

The following is a screenshot of the TextView in the demo in Testactivity caused by a static variable reference to a memory leak caused by an inability to recycle.

Leakcanary is simpler to use, adding dependent engineering first:

dependencies {
debugcompile ' com.squareup.leakcanary:leakcanary-android:1.3 '
releasecompile ' com.squareup.leakcanary:leakcanary-android-no-op:1.3 '

Second, initialize in the application OnCreate () method.

public class Exampleapplication extends application {
@Override public void OnCreate () {
super.oncreate ();
Leakcanary.install (this);
}

After these two steps can be used. Leakcanary.install (this) returns a predefined Refwatcher, and a activityrefwatcher is also enabled to automatically monitor the leak after calling Activity.ondestroy () Activity If you need to listen for fragment, register in the OnDestroy () method of fragment:

Public abstract class Basefragment extends Fragment {
@Override public void OnDestroy () {
Super.ondestroy ();
Refwatcher Refwatcher = Exampleapplication.getrefwatcher (Getactivity ());
Refwatcher.watch (this);
}

Of course, need to listen to a variable, directly to its watch can be.

Refwatcher Refwatcher = {...};
We expect Schrodingercat to be gone soon (or does), let's watch it.

It is to be noted that the use of leakcanary in eclipse requires a statement of the heap occupancy analysis and the service displayed in the Androidmanifest file:

<service
android:name= "Com.squareup.leakcanary.internal.HeapAnalyzerService"
android:enabled= false "
android:process=": Leakcanary "/>
<service
android:name=" Com.squareup.leakcanary.DisplayLeakService "
android:enabled=" false "/>
<activity
android:name = "Com.squareup.leakcanary.internal.DisplayLeakActivity"
android:enabled= false "
android:icon=" @ Drawable/leak_canary_icon "
android:label=" @string/leak_canary_display_activity_label "
android: Taskaffinity= "Com.squareup.leakcanary"
android:theme= "@style/leak_canary_leakcanary.base" >
< intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category "Android.intent.category.LAUNCHER"/>
</intent-filter>

Note: Heapanalyzerservice has adopted multiple processes android:process= ": leakcanary".

The use of the above open source tools is relatively simple, for detailed use, please refer to its GitHub address.

Four, some messy summary

Common causes of memory leaks:

• Static objects: Listeners, broadcasts, WebView;
this$0: Thread, timer, Handler;
• System: Textline, Input method, audio

Fallback Reclaim Memory:

An activity leak can lead to the inability to release the Bitmap/drawingcache, which is referenced by the activity, and fallback recycling refers to an attempt to reclaim resources held by a leaked activity. Starting from Rootview in OnDestroy, recursive release of all child view involved in the picture, background, Drawingcache, listeners and other resources.

Ways to reduce runtime memory:

1. Reduce the memory occupied by bitmap: 1 to prevent bitmap occupy resources too large, 2. The X system opens the innativealloc;4.x system in Bitmapfactory.options using Facebook's fresco library, which puts the picture resources in the native. 2 pictures should be loaded on demand, the size of the picture should not exceed the view size. 3) Unified Bitmap Loader: Picasso/fresco. 4 There is a waste of pixels in the picture.

2. Self-memory footprint monitoring: 1 Implementation principle: Get MaxMemory through runtime, and Totalmemory-freememory is the Dalvik memory that is really used now. 2) operation mode: Check this value regularly, reach 80% to release various cache resources (bitmap cache)

3. Use multiple processes. For WebView, gallery and so on, due to the existence of memory system leaks, you can use a separate process.

Related Article

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.