0

我在我的使用下面的代码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;
        }
    }
}
4

2 回答 2

0

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

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 
        }
    }
}

如果您需要其静态变量之一的活动引用,您可以将其传递给 Intent Extras,或者您想调用活动的静态函数,广播接收器将是执行此操作的更好选择。

于 2016-12-08T06:56:48.737 回答
0

如果您从活动开始服务并在该服务中使用一些活动数据。您可以按意图传递它们。

    Intent intent = new Intent(this,MyService.class);
    intent.putExtra("data", "some_value");
    startService(intent);
于 2016-12-08T06:37:33.343 回答