警告:此AsyncTask类应该是静态的,否则可能会发生泄漏 [英] Warning: This AsyncTask class should be static or leaks might occur

查看:572
本文介绍了警告:此AsyncTask类应该是静态的,否则可能会发生泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中收到一条警告,指出:

I am getting a warning in my code that states:


此AsyncTask类应该是静态的,或者可能会泄漏(匿名android。 os.AsyncTask)

This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)

完整的警告是:


此AsyncTask类应该是静态的或可能发生泄漏(匿名android.os.AsyncTask)
静态字段将泄漏上下文。非静态内部类对其外部类具有隐式引用。如果该外部类例如是Fragment或Activity,则此引用意味着长时间运行的处理程序/加载器/任务将持有对该活动的引用,从而防止该活动获取垃圾。同样,对这些较长运行实例的活动和片段的直接字段引用也可能导致泄漏。 ViewModel类不应指向视图或非应用程序上下文。

This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask) A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.

这是我的代码:

 new AsyncTask<Void,Void,Void>(){

        @Override
        protected Void doInBackground(Void... params) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
                }
            });

            return null;
        }
    }.execute();

我该如何纠正?

推荐答案

非静态内部类包含对包含类的引用。当您将 AsyncTask 声明为内部类时,它的寿命可能比包含 Activity 类的寿命更长。这是因为对包含类的隐式引用。

Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.

要解决您的问题,请使用静态嵌套类而不是匿名,本地和内部类,或者使用顶级类。

To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.

这篇关于警告:此AsyncTask类应该是静态的,否则可能会发生泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆