android 优化
1.图像缩放
1
2
3
4
5
6
7
8
9
|
private void compressImage(String pathName) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 10 ; // 为原来图形的1/10 Bitmap bitmap = BitmapFactory.decodeFile(pathName ,options); // 显示图像到控件 ImageView imageView = new ImageView(getApplicationContext()); imageView.setImageBitmap(bitmap); bitmap.recycle(); } |
2.及时释放对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
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>>(); mDrawable = new WeakHashMap<Integer, WeakReference<Drawable>>(); } public Bitmap getmBitmaps( int resource) { if (mActive) { if (!mBitmaps.containsKey(resource)) { mBitmaps.put(resource, new WeakReference<Bitmap>(BitmapFactory.decodeResource(getResources(), resource))); return ((WeakReference<Bitmap>)mBitmaps.get(resource)).get(); } } return null ; } public Drawable getDrawable( int resource){ if (mActive) { if (!mDrawable.containsKey(resource)) { mDrawable.put(resource, new WeakReference<Drawable>(getResources().getDrawable(resource))); return ((WeakReference<Drawable>)mDrawable.get(resource)).get(); } } return null ; } public void recycleBitmaps(){ Iterator iterator = mBitmaps.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry type = (Map.Entry) iterator.next(); ((WeakReference<Bitmap>)type.getValue()).get().recycle(); } } private ImageManager setActive( boolean b) { // TODO Auto-generated method stub mActive = b; return this ; } public boolean isActive(){ return mActive; } } |
3.
哟话网络连接,
首先检测网络是否正常, 如没有网络就不执行相应的程序,
检查网络连接的演示代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public boolean isConnected(){ ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); NetworkInfo info = manager.getActiveNetworkInfo(); if (info== null ||!manager.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&&!telephonyManager.isNetworkRoaming()){ return info.isConnected(); } else { return false ; } } |