Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
587 views
in Technique[技术] by (71.8m points)

android - Passing a activity context into a static method, memory leak potential?

I've seen this particular technique for launching activities and it seems to me like a bad idea because of static contexts but I was hoping someone might have a legit reason behind this approach.

The activity you want to launch implements a static launch(Context context) method that sets up the intent, flags, etc and finally starts the activity.

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

Then a DifferentActivity could go and launch SomeOtherActivity with one line.

SomeOtherActivity.launch(DifferentActivity.this);

I like how it allows you to setup the flags in the activity away from the DifferentActivity that is launching it but it doesnt seem like a good enough reason to rationalize passing that activity's context into a static method.

Wouldn't this cause DifferentActivity to not be garbage collected because now that static method has a reference to it? This seems like a memory leak to me and probably not a good idea to do just to be able to keep the flags contained in the activity that is being created.

Is there something I'm missing here that makes this a good practice to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Passing something into a static function isn't a potential memory leak. Storing a variable in a static variable is. This technique is perfectly safe. Its one I'd even recommend, as you can pass in variables to the function and store them in extras inside the class that is going to use those extras, reducing the number of places that need to know of their existence and how they're laid out


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...