Passing activity context to static method, memory leak potential?

I saw this particular trigger technique, and it seems like a bad idea to me due to static contexts, but I was hoping that someone might have a legitimate reason for this approach.

The activity you want to run implements the static start method (context context), which sets the intent, flags, etc. and finally launches activity.

public static void launch(Context context){ Intent i = new Intent(context, SomeOtherActivity.class); // flag stuff context.startActivity(i); } 

Then, the DifferentActivity function can be implemented and SomeOtherActivity can be run on a single line.

 SomeOtherActivity.launch(DifferentActivity.this); 

I like the way it allows you to set flags in activity away from the DifferentActivity function being expanded, but this does not seem to be a good enough reason to rationalize the transfer of this activity context to the static method.

Won't this cause DifferentActivity to not be garbage collected, because now this static method has a reference to it? This seems like a memory leak to me and probably not a good idea to be able to store flags in the activity being created.

Is there something I am missing here that makes this a good practice?

+5
source share
1 answer

Passing anything to a static function is not a potential memory leak. Saving a variable in a static variable. This method is absolutely safe. I would even recommend it, since you can pass variables to functions and store them in additional classes inside the class that will use these additional functions, reducing the number of places you need to know about their existence and how they are laid out

+8
source

Source: https://habr.com/ru/post/1266876/


All Articles