Android 内存优化

2020-11-05  本文已影响0人  编程_书恨少

1.java的四种引用方式
强引用,软引用,弱引用,虚引用


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 强引用 对象类型 变量名(实例)= 对象的构造方法
        // 强引用,不管怎样都不会回收对象,内存溢出
        String str = new String("abc");

        // 软引用 当内存实在不足的情况下,才会释放掉它的引用对象
        SoftReference<String> softReference = new SoftReference<String>(str);

        // 弱引用  只要系统产生GC,就会回收
        WeakReference<String> weakReference = new WeakReference<String>(str);

        str = null;
        System.out.println("强引用" + str);

        softReference.clear();
        System.out.println("软引用" + softReference.get());

        System.gc();
        System.out.println("弱引用" + weakReference.get());


        // 虚引用 用来判断对象是否已经被回收
//        PhantomReference<String> phantomReference = new PhantomReference<>()

    }
}

打印的结果有点问题,弱引用在GC回收之后应该也是null才对的


image.png

如果换一种写法

//        String str = new String("abc");
        String str = "abc";

只改变str的创建方法,这时候弱引用就会有值了,是"abc",因为GC只会回收堆内存中的对象,而直接 String str = "abc";这样写,abc是位于常量区的

2.LeakCanary检测内存泄漏
内存泄漏:对无用对象的引用一直未释放,就会造成内存泄漏。
造成内存泄漏的原因:

第一种情况:

1.内部类会隐式持有外部类,如果说内部类进行了耗时操作,还没有等操作结束,用户进行点击返回,弹出了当前的activity,那么内部类也不会释放这个activity,这样就会造成内存泄漏

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        startTask();
    }

    private void startTask() {
        MyThread myThread = new MyThread();
        myThread.start();
    }
    // 内部类隐式持有了外部类Activity的引用,所以内部类中的任务没有执行完,    
    //Activity的引用就不会被释放
    public class MyThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                Log.d(getClass().getSimpleName(), "run: " + i);
                SystemClock.sleep(1000);
            }
        }
    }
}

LeakCanary会给出对应的通知


image.png

解决方案:
1.将内部类转移出去,变成独立的类
2.将内部类变成静态内部类,这样也不会持有外部类的实例
static class MyThread extends Thread
3.内部类通过弱引用来使用外部类的非静态属性和方法

public  class MainActivity extends AppCompatActivity {

    private boolean isDestroy = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        startTask();
    }

    private void startTask() {
        MyThread myThread = new MyThread(MainActivity.this);
        myThread.start();
    }
    

    //内部类隐式的持有了外部类Activity的引用,所有内部类中任务没执行完,Activity的引用就不会被释放
    //内部类改成了静态的内部类之后,内部类将不会再隐式持有外部类的引用
    public static class MyThread extends Thread{

        //通过使用弱引用来拿到外部类Activity的非静态属性和方法
        private WeakReference<MainActivity> mWeakReference = null;

        MyThread(MainActivity activity){
            mWeakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void run() {
            //写在run方法中的逻辑会在MyThread线程中后台执行
            MainActivity mainActivity = mWeakReference.get();
            //为了健壮性
            if(mainActivity!=null){
                    for (int i = 0; i < 20; i++) {
                        if(!mainActivity.isDestroy){
                            Log.d(getClass().getSimpleName(), "run: " + i);
                            SystemClock.sleep(1000);
                        }
                    }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroy = true;
    }
}

这样在退出当前的Activity之后,内部类就不会持有Activity的实例了,不会发生内存泄漏
所以造成内存泄漏的原因是两点同时发生
1.内部类隐式持有外部类
2.内部类做了耗时操作,且未完成的情况下外部类就销毁了

第二种情况

内部类handler出现内存泄漏
1.内部类持有了外部类实例
2.消息延迟发送的情况下才会产生内存泄漏
解决方案也和之前的类似

public class MainActivity extends AppCompatActivity {

    private static final int MESSAGE_SEND = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        startSendMessage();
    }

    private void startSendMessage() {
        MyHandler myHandler = new MyHandler(MainActivity.this);
        Message message = Message.obtain();
        message.what = MESSAGE_SEND;
        message.obj = "这是一段来自三体的消息";
        myHandler.sendMessageDelayed(message,20000);
//        myHandler.sendMessage(message);
    }


    //创建一个内部类handler
    //1 将内部类作为static的
    //2 把Handler写成一个独立的java文件

    private static class MyHandler extends Handler{

        private WeakReference<MainActivity> mWeakReference = null;

        MyHandler(MainActivity activity){
            mWeakReference = new WeakReference<MainActivity>(activity);
        }

        //处理发送过来的消息的
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity mainActivity = mWeakReference.get();
            if(mainActivity==null){
                return;
            }
            //接收
            switch (msg.what) {
                    case MESSAGE_SEND:
                        String obj = (String) msg.obj;
                        Toast.makeText(mainActivity, obj, Toast.LENGTH_SHORT).show();
                        break;
                    }
        }
    }
}

第三种情况

非静态内部类的静态实例
1.非静态内部类会隐式持有外部类的引用
2.静态的实例是属于类对象的,不会跟随实例对象的销毁而销毁

public class MainActivity extends AppCompatActivity {

    //一个静态的实例   静态的实例不会跟着外部类的关闭而销毁
    public static User user = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        user = new User();
    }

    //一个简单的非静态内部类,隐式持有外部类的引用
    private class User{
        User(){

        }
    }
}

第四种情况

单例对象持有的对象被销毁了

public class ToastManager {

    private ToastManager() {

    }

    private Context mContext = null;
    private ToastManager(Context context) {
        mContext = context;
    }

    private static ToastManager mToastManager = null;
    public static ToastManager getInstance(Context context) {
        if (mToastManager == null) {
            synchronized (ToastManager.class) {
                if (mToastManager == null) {
                    mToastManager = new ToastManager(context);
                }
            }
        }
        return mToastManager;
    }


    public void showToast(String text) {
        Toast.makeText(mContext,text, Toast.LENGTH_SHORT).show();
    }
}


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    void btnClick(View view){
        ToastManager manager = ToastManager.getInstance(MainActivity.this);
        manager.showToast("hello world");
    }
}

这样在点击按钮的时候,MainActivity的对象就被单例持有了,当MainActivity销毁的时候,单例还会继续持有它,所以会造成内存泄漏。当然我们平时编码并不会这样写,我们会直接使用 ToastManager manager = ToastManager.getInstance(getApplicationContext());来代替,这样就没问题了。

2.context上下文的作用域

image.png

当然在startService的时候尽量不要用Activity的context,有内存泄漏的风险

3.LeakCanary观察特定的对象。
之前的配置是创建MyApplication,复制官方的代码,这样只能检测Activity的内存泄漏

public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        //检测内存泄漏的LeakCanary的初始化
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
    }
}

,如果要检测比如Fragment的内存泄漏,需要换一种写法,需要保存返回的mRefWatcher

public class MyApplication extends Application {

    public static RefWatcher mRefWatcher;

    @Override
    public void onCreate() {
        super.onCreate();
        //检测内存泄漏的LeakCanary的初始化
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        mRefWatcher = LeakCanary.install(this);
    }
}

然后用mRefWatcher去检测每一个类的内存泄漏情况

public class MyFragment extends Fragment {

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        FragmentActivity activity = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Button button = new Button(container.getContext());
        button.setText("我是Fragment的TextView");
        button.setTextSize(50);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyThread myThread = new MyThread();
                myThread.start();
            }
        });
        return button;
    }

    //演示内存泄漏,来一个内部类Thread
    public class MyThread extends Thread {

        @Override
        public void run() {
            for (int i = 0; i < 20; i++) {
                Log.d(getClass().getSimpleName(), "run: " + i);
                SystemClock.sleep(1000);
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        //Fragment已经被销毁,如果这个时候调用LeakCanary的观察对象的watch方法,如果他发现还有引用,认为是内存泄露
        MyApplication.mRefWatcher.watch(MyFragment.this);
    }
}

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyFragment myFragment = new MyFragment();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = manager.beginTransaction();
        fragmentTransaction.add(R.id.fl,myFragment);
        fragmentTransaction.commit();
    }
}

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.it520.fragmentleak.MainActivity">

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
</RelativeLayout>
上一篇下一篇

猜你喜欢

热点阅读