Android内存优化及内存机制学习

来源:互联网 发布:七天网络阅卷查分下载 编辑:程序博客网 时间:2024/05/07 14:59
Android内存机制学习:--只有自己变优秀了才能遇到更优秀的别人
1、在后台耗电的只有带服务的应用,没有带服务的应用在后台是完全不耗电的。


2、Android进程
   .前台进程(屏幕上正在显示的进程和Dialer,Storage,Google Search等一些系统进程)
   .可见进程(不在前台但依然可见的进程,比如时钟,天气,输入法)
   .服务进程(进程中运行着一个service,比如后台播放音乐,后台下载数据)
   .后台进程
   .空进程(进程中不包含任何活跃的应用组件)
   
3、内存优化:
   .使用优化过的数据容器
   --当key为Integer类型时使用SparseArray,SparseBooleanArray,LongSparseArray代替HashMap
   --HashMap<Integer,E> map = new HashMap<Integer,E>()替换为SparseArray<E> array = new SparseArray<E>();
   .使用IntentService代替Service
   --Service默认在UI线程中执行,IntentService在后台执行
   --Service在start后如果没有手动stop会一直存在,IntentService在执行完后自动退出
   .枚举类Enum相比静态类需要两倍甚至更多的内存,经测试静态类的性能比枚举类的性能也要好,所以要尽量避免使用Enum。
   --public enum Age{_12,_16,_19}
   --public static class AG{}
   .使用混淆器移除不必要的代码
   .尽量不要因一两个特性而使用大体积类库
   .频繁修改使用StringBuffer或StringBuilder
   .对于常量,请尽量使用static final
   .对象不用时最好显式置为null
   .利用系统资源(减少内存,缩减程序包大小)
   --系统定义的id @android:id/list
   --系统的图片资源 @android:drawable/ic_menu_attachment
   --系统的文字串资源 @android:string/yes
   --系统的Style android:textAppearance="?android:attr/textAppearanceMedium"
   --系统的颜色定义 android:background="@android:color/transparent"
   .通用模块抽离
   --<include layout="@layout/navigator_bar"/>
   .使用ViewStub(在布局文件中声明后,若是没有代码动态加载,则隐藏并且不占内存空间)
   --使用场景:网络请求失败页面的显示,引导页(需要的时候才加载)
   --ViewStub只能加载一次,重复加载会出现异常,ViewStub只要加载过一次,自身就会被移除,并把自身的内容转给父布局。
   <ViewStub
        android:id="@+id/vs"
        android:layout="@layout/viewstub"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
使用的时候加载:
viewStub.inflate();
    //textView  = (TextView) viewStub.findViewById(R.id.hello_tv);空指针
    textView  = (TextView) findViewById(R.id.hello_tv);