android性能优化1

时间:2022-04-25
本文章向大家介绍android性能优化1,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、在使用Gallery控件时,如果载入的图片过多,过大,就很容易出现OutOfMemoryError异常,就是内存溢出。这是因为Android默认分配的内存只有几M,而载入的图片如果是JPG之类的压缩格式,在内存中展开时就会占用大量的空间,也就容易内存溢出。这时可以用下面的方法解决:

ImageView i = new ImageView(mContext);  
          BitmapFactory.Options options=new BitmapFactory.Options();  
          options.inSampleSize = 10;  
 //貌似这个options的功能是返回缩略图,10即表示长和宽为原来的1/10,即面积为原来的1/100 
 //缩略图可以减少内存占用 
          Bitmap bm = BitmapFactory.decodeFile(lis.  
 get(position).toString(),options);  
          i.setImageBitmap(bm);  
          bm.recycle();  
 //资源回收 

二、统一管理位图资源,适时释放资源

class ImageManager {     
 private WeakHashMap<Integer, WeakReference<Bitmap>> mBitmaps;     
 private WeakHashMap<Integer, WeakReference<Drawable》> mDrawables;     
 
 private boolean mActive = true;     
 
 public ImageManager() {     
        mBitmaps = new WeakHashMap<Integer, WeakReference<Bitmap>>();     
        mDrawables = new WeakHashMap<Integer, WeakReference<Drawable>>();     
    }     
 
 
 public Bitmap getBitmap(int resource) {     
 if (mActive) {     
 if (!mBitmaps.containsKey(resource)) {     
                mBitmaps.put(resource,     
 new WeakReference<Bitmap>(BitmapFactory.decodeResource(MainActivity.getContext().getResources(), resource)));     
            }     
 return ((WeakReference<Bitmap>)mBitmaps.get(resource)).get();     
        }     
 return null;     
    }     
 
 public Drawable getDrawable(int resource) {     
 if (mActive) {     
 if (!mDrawables.containsKey(resource)) {     
                mDrawables.put(resource, new WeakReference<Drawable>(getApplication().getResources().getDrawable(resource)));     
            }     
 return ((WeakReference<Drawable>)mDrawables.get(resource)).get();     
        }     
 return null;     
    }     
 
 public void recycleBitmaps() {     
        Iterator itr = mBitmaps.entrySet().iterator();     
 while (itr.hasNext()) {     
            Map.Entry e = (Map.Entry)itr.next();     
            ((WeakReference<Bitmap>) e.getValue()).get().recycle();     
        }     
        mBitmaps.clear();     
    }     
 
 public ImageManager setActive(boolean b) {     
        mActive = b;     
 return this;     
    }     
 
 public boolean isActive() {     
 return mActive;     
    }     
}    

三、网络连接往往是耗电量比较大的 那我们可以优化一下在需要网络连接的程序中,首先检查网络连接是否正常,如果没有网络连接,那么就不需要执行相应的程序。

检查网络连接的方法如下:

private boolean isConnected(){  
        ConnectivityManager mConnectivity = (ConnectivityManager) this.getSystemService(CONNECTIVITY_SERVICE);    
        TelephonyManager mTelephony = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);  
 
 // 检查网络连接,如果无网络可用,就不需要进行连网操作等 
        NetworkInfo info = mConnectivity.getActiveNetworkInfo();  
 if (info == null ||  
                !mConnectivity.getBackgroundDataSetting()) {  
 return false;  
        }  
 //判断网络连接类型,只有在3G或wifi里进行一些数据更新。 
 int netType = info.getType();  
 int netSubtype = info.getSubtype();  
 if (netType == ConnectivityManager.TYPE_WIFI) {  
 return info.isConnected();  
        } else if (netType == ConnectivityManager.TYPE_MOBILE  
                && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS  
                && !mTelephony.isNetworkRoaming()) {  
 return info.isConnected();  
        } else {  
 return false;  
        }  
    }  

四、网络间的数据传输也是非常耗费资源的,这包括传输方式和解析方式

来看一个表格

其中 Tree Parse 是DOM解析 Event/Stream是SAX方式解析

很明显,使用流的方式解析效率要高一些,因为DOM解析是在对整个文档读取完后,再根据节点层次等再组织起来。而流的方式是边读取数据边解析,数据读取完后,解析也就完毕了。

在数据格式方面,JSON和Protobuf效率明显比XML好很多,XML和JSON大家都很熟悉。

从上面的图中我们可以得出结论就是尽量使用SAX等边读取边解析的方式来解析数据,针对移动设备,最好能使用JSON之类的轻量级数据格式为佳。

五、传输数据经过压缩 目前大部门网站都支持GZIP压缩,所以在进行大数据量下载时,尽量使用GZIP方式下载,可以减少网络流量。

使用方法如下所示:

HttpGet request =  
 new HttpGet("http://example.com/gzipcontent");  
    HttpResponse resp =  
 new DefaultHttpClient().execute(request);  
    HttpEntity entity = response.getEntity();  
    InputStream compressed = entity.getContent();  
    InputStream rawData = new GZIPInputStream(compressed);  

六、有效管理Service 后台服务就相当于一个持续运行的Acitivity  如果开发的程序后台都会一个service不停的去服务器上更新数据,在不更新数据的时候就让它sleep,这种方式是非常耗电的,通常情况下,我们可以使用AlarmManager来定时启动服务。如下所示,第30分钟执行一次。

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