Android:内存泄漏

Android: Memory Leak

我在 activity class:

中使用下面的代码
public static Activity list_Addresses_Activity;

在我的 onCreate 中,我使用了这个:

list_Addresses_Activity = this;

但它抛出如下错误:

Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

我需要从 static 使用它,因为我将在我的 Service class.

中使用它

我的 CloseActivies.class :

public class CloseActivies {
    Activity a;
    Activity b;
    Activity c;

    protected void CLSActivities(Activity ListAddresses, Activity ListOrder, Activity SendReports) {
        a = ListAddresses;
        b = ListOrder;
        c = SendReports;
        if (ListAddressesActivity.FlagLiveAddress && a != null) {
            Log.e("ADASFSDAGWEG", "X");
            a.finish();
            ListAddressesActivity.FlagLiveAddress = false;
        }
        if (ListOrderActivity.FlagLiveOrder && b != null) {
            Log.e("ADASFSDAGWEG", "Y");
            b.finish();
            ListOrderActivity.FlagLiveOrder = false;
        }
        if (SendReportsActivity.FlagSendReport && c != null) {
            Log.e("ADASFSDAGWEG", "Z");
            c.finish();
            SendReportsActivity.FlagSendReport = false;
        }
    }

    protected void CLSActivities() {
        if (ListAddressesActivity.FlagLiveAddress && a != null) {
            Log.e("ADASFSDAGWEG", "X");
            a.finish();
            ListAddressesActivity.FlagLiveAddress = false;
        }
        if (ListOrderActivity.FlagLiveOrder && b != null) {
            Log.e("ADASFSDAGWEG", "Y");
            b.finish();
            ListOrderActivity.FlagLiveOrder = false;
        }
        if (SendReportsActivity.FlagSendReport && c != null) {
            Log.e("ADASFSDAGWEG", "Z");
            c.finish();
            SendReportsActivity.FlagSendReport = false;
        }
    }
}

如果您从 activity 开始服务并在该服务中使用 activity 的一些数据。您可以故意传递它们。

    Intent intent = new Intent(this,MyService.class);
    intent.putExtra("data", "some_value");
    startService(intent);

这会导致内存泄漏,因为您的服务 class 正在单独的线程上工作,并且将静态引用传递给您的 activity 会将实例保留在内存中,即使 activity 被解雇而不是垃圾收集,一种更安全的方法是将您的 activity 的引用作为参数传递给您的服务,并将其存储在像这样的弱引用中

public class MyIntentService extends IntentService {

    private final WeakReference<Context> mContextWeakReference;

    public MyIntentService() {
        super("MyIntentService");
    }

    public static void startActionFoo(Context context) {
        mContextWeakReference = new WeakReference<>(context);
        Intent intent = new Intent(context, MyIntentService.class);
        context.startService(intent);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Context context = mContextWeakReference.get();
        if(context != null) {
            //do your work as since context is not null means
            //activity is still present and if activity is dismissed
            //context will come null 
        }
    }
}

如果您需要 activity 对其静态变量之一的引用,您可以在意向附加中传递它,或者您想调用 activity 的静态函数,广播接收器会更好选择这样做。