androidandroid-studio-2.2

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


Android Studio:

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

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)?

Examples:

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

or

        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);

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.


Solution

  • 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.

    This is how your method should look:

    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.