Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - Passing Activity or Context to other instance

Can you please tell me whats the best practice to pass activity or context to other instance(;)

But...,

  • What is better to pass? Activity or Context
  • Is good idea to have the Activity as Global (public static Activity activity)

here is my code. What would you change? (based on good android practices)

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Passing an Activity into another object that does not specifically require the Activity object is usually a bad idea. Activity extends Context so it works to satisfy a method that requires Context.

In your case, you can get the Context from the View that is passed into the method. However, if you need the Context for other purposes, you should avoid passing Activity and do something like Activity.getApplicationContext().

The reason for this is if the object you pass an Activity into lives longer than the Activity, the reference to the Activity will prevent Android from doing proper Garbage Collection (GC) and consume unnecessary memory. This is called a "memory leak".

EDIT:

To handle situations where you need to call Activity.findViewById() keep these things in mind. First, that is a View method (http://developer.android.com/reference/android/view/View.html#findViewById(int)) so be sure to call it from the correct view.

Second, if you need a View from an Activity you should pass it in as a WeakReference


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...