警告:请勿将Android上下文类放在静态字段中;这是内存泄漏(并且还会中断即时运行) [英] Warning: Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)

查看:124
本文介绍了警告:请勿将Android上下文类放在静态字段中;这是内存泄漏(并且还会中断即时运行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android Studio:

Android Studio:

请勿将Android上下文类放在静态字段中;这是一个 内存泄漏(还会中断即时运行)

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

所以有2个问题:

#1如何在没有用于上下文的静态变量的静态方法中调用startService? #2如何通过静态方法(相同)发送localBroadcast?

So 2 questions:

#1 How do you call a startService from a static method without a static variable for context?
#2 How do you send a localBroadcast from a static method (same)?

示例:

public static void log(int iLogLevel, String sRequest, String sData) {
    if(iLogLevel > 0) {

        Intent intent = new Intent(mContext, LogService.class);
        intent.putExtra("UPDATE_MAIN_ACTIVITY_VIEW", "UPDATE_MAIN_ACTIVITY_VIEW");
        mContext.startService(intent);
    }
}

        Intent intent = new Intent(MAIN_ACTIVITY_RECEIVER_INTENT);
        intent.putExtra(MAIN_ACTIVITY_REQUEST_FOR_UPDATE, sRequest));
        intent.putExtra(MAIN_ACTIVITY_DATA_FOR_VIEW, sData);
        intent.putExtra(MAIN_ACTIVITY_LOG_LEVEL, iLogLevel);
        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);

不使用mContext来执行此操作的正确方法是什么?

What would be the correct way to do this without using mContext?

注意:我想我的主要问题可能是如何将上下文传递给调用方法所在的类.

NOTE: I think my main question might be how to pass context to a class from which the calling method lives.

推荐答案

只需将其作为参数传递给您的方法.仅出于启动Intent的目的而创建Context的静态实例是没有意义的.

Simply pass it as a parameter to your method. There is no sense in creating a static instance of Context solely for the purpose of starting an Intent.

这是您的方法的外观:

public static void log(int iLogLevel, String sRequest, String sData, Context ctx) {
    if(iLogLevel > 0) {

        Intent intent = new Intent(ctx, LogService.class);
        intent1.putExtra("UPDATE_MAIN_ACTIVITY_VIEW", "UPDATE_MAIN_ACTIVITY_VIEW");
        ctx.startService(intent);
    }
}

有关问题的评论的更新:从启动活动(通过构造函数参数或方法参数)直至所需的级联上下文.

Update from comments on question: Cascade the context from the initiating activity (via constructor parameters or method parameters) right up to the point you need it.

这篇关于警告:请勿将Android上下文类放在静态字段中;这是内存泄漏(并且还会中断即时运行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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