Android优化系列——性能优化(图片缓存,网络链接,Service定时)

( 整理来自Android优化技术详解一书)

  • 在使用Gallery控件时,如果加载的图片过多,过大,就容易出现OutOfMemoryError异常,就是内存溢出。
ImageView i = new ImageView(mContext);
BitmapFactory.Options options = new BitmapFactory.Options();
//返回缩率图,长宽为原来的10分之一,面积为1/100
options.inSampleSize = 10;
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>> mDrawable;
    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(!mBitmaps.containsKey(resource)){
                    mBitmaps.put(resource, new WeakReference<Drawable>(getApplication().getResources().getDrawable(resource)));
                }
                return ((WeakReference<Drawable>)mBitmaps.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;
    }

}

弱引用也是用来描述非必需对象的,但是它的强度比软引用更弱一些,被弱引用关联的对象只能生存到下一次垃圾收集发生之前。当垃圾收集器工作时,无论当前内存是否足够,都会回收掉只被弱引用关联的对象。在JDK 1.2之后,提供了WeakReference类来实现弱引用。

  • 检查网络链接的方法
private boolean isConnected(){
        ConnectivityManger mConnectivity = (ConnectivityManger)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;
        }
}
  • 目前大部分网站都支持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后台服务就相当于持续运行的Activity。如果开发程序后台都有一个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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值