290
搜狐
Introducing AQuery: jQuery for Android
一、內存溢出現在的智能手機內存已經足夠大,但是對於一個應用程序來說智能手機當中稀缺的內存,仍然是應用程序的一大限製。在Android應用程序開發當中,最常見的內存溢出問題(OOM)是在加載圖片時出現的,尤其是在不知道圖片大小的情況下。
潛在的內存溢出操作主要包括以下幾點:
從網絡當中加載用戶特定的圖片。因為直到我們在下載圖片的時候我們才知道圖片的大小。
向Gallery加載圖片。因為現在智能手機的攝像頭有很高的分辨率,在加載圖片的時候需要最圖片進行處理,然後才能正常的使用。
請注意一點,Android係統是從係統全局的觀念來分配內存以加載圖片的,這就意味著,即使你的應用有足夠大的內存可用,內存溢出問題(out of memroy,OOM)仍然可能出現,因為所有的應用共享一個加載圖片的內存池(我們使用BitmapFactory進行解析)。
二、解決內存溢出問題
原文(Downsampling為了好理解,解釋為,程序A)。程序A通過調整相鄰的像素,同時使其均衡化來降低圖片的分辨率。因為不管問題圖片是因為太大而不能再手機上正常顯現,這個圖片都會縮短其寬度以在ImageView當中顯示,當圖片在ImageView當中顯示時,我們會因為加載一些沒有必要的原始圖片而浪費掉內存。
因此,更加有效的加載圖片的時機是在其初始化處理的時候。
以下是處理代碼
private static Bitmap getResizedImage(String path, byte[] data, int targetWidth){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); int width = options.outWidth; int ssize = sampleSize(width, targetWidth); options = new BitmapFactory.Options(); options.inSampleSize = ssize; Bitmap bm = null; try{ bm = decode(path, data, options); }catch(OutOfMemoryError e){ AQUtility.report(e); } return bm; } private static int sampleSize(int width, int target){ int result = 1; for(int i = 0; i < 10; i++){ if(width < target * 2){ break; } width = width / 2; result = result * 2; } return result; }三、AQuery
當在Android應用程序開發當中使用AQuery組件時,處理這個問題會變的更加的簡單。
1、當從網絡當中下載圖片時,我們僅僅需要以下的幾句代碼:
- String url = "https://farm6.static.flickr.com/5035/5802797131_a729dac808_b.jpg";
- aq.id(R.id.image1).image(imageUrl, true, true, 200, 0);
2、當加載已有圖片時,我們需要的代碼如下:
- File file = new File(path);
- //load image from file, down sample to target width of 300 pixels
- aq.id(R.id.avatar).image(file, 300);
最後更新:2017-04-02 17:28:39