In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "what is Context". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is Context".
Activity mActivity = new Activity ()
As an Android developer, I wonder if you have ever thought about this question, can Activity new? Android's application development uses Java language, and Activity is essentially an object, so what's wrong with the above writing? I guess a lot of people don't know what to say. Unlike Java programs, Android programs can be run by simply creating a class and writing a main () method. The Android application model is an application design pattern based on components. The operation of components requires a complete Android engineering environment, in which Activity, Service and other system components can work normally. However, these components can not be created in the ordinary way of Java objects, and new can create instances at once. Instead, they should have their own context, that is, the Context we are talking about here. It can be said that Context is a core functional class that keeps the components of the Android program working properly.
What on earth is Context?
The Chinese translation of Context is: context; context; background; environment, which we often call "context" in development, so what exactly does this "context" mean? In Chinese, we can understand it as context, and in the program, we can understand it as an environment in which the current object is in the program, a process of interaction with the system. For example, Wechat chat, the "environment" refers to the chat interface and related data requests and transmission, Context is involved in loading resources, starting Activity, obtaining system services, creating View and other operations.
So what on earth is Context? An Activity is a Context, and a Service is a Context. Android programmers abstract the "scenario" into Context classes, and they think that every interaction between the user and the operating system is a scene, such as calling and texting, which is a scenario with an interface, and some scenarios without an interface, such as a service running in the background (Service). An application can be thought of as a work environment in which users switch to different scenarios, just like a receptionist who may need to receive guests, print documents, or answer customer calls. and these are called different scenarios, and the receptionist can call it an application.
How to understand Context vividly
The above concept uses a popular way of understanding Context as "context" or "scene", if you still find it abstract and difficult to understand. Here I give a may not be very appropriate metaphor, I hope to help you understand: an Android application, can be understood as a movie or a TV series, Activity,Service,Broadcast Receiver,Content Provider these four components are like the four protagonists in this play: Hu GE, Huo Jianhua, Poetry, Baby. They were decided by the crew (system) from the very beginning, and the whole play is led by these four actors, so these four protagonists can't all be played by random individuals (new) on the street. With actors, of course, there must be cameras to shoot, ah, they must pass on the play to the audience through the Context, which means that the four major components (four protagonists) must work in the Context environment (camera lens). As for Button,TextView,LinearLayout, these controls are like supporting roles or extras in this play. They are obviously not so important. Any passerby An and B can act (can new an object), but they also have to face the camera (working in a Context environment), so Button mButton=new Button (Context) is OK. Although it is not very appropriate, it is easy to understand. I hope it will be helpful.
Context in source code
/ * Interface to global information about an application environment. This is * an abstract class whose implementation is provided by * the Android system. It * allows access to application-specific resources and classes, as well as * up-calls for application-level operations such as launching activities, * broadcasting and receiving intents, etc. / public abstract class Context {/ * File creation mode: the default mode, where the created file can only * be accessed by the calling application (or all applications sharing the * same user ID). * @ see # MODE_WORLD_READABLE * @ see # MODE_WORLD_WRITEABLE * / public static final int MODE_PRIVATE = 0x0000; public static final int MODE_WORLD_WRITEABLE = 0x0002; public static final int MODE_APPEND = 0x8000; public static final int MODE_MULTI_PROCESS = 0x0004;. . . }
The comments in the source code interpret Context this way: Context provides an interface to global information about the application environment. It is an abstract class whose execution is provided by the Android system. It allows access to resources and types characterized by applications, and is a context that governs some resources (application environment variables, etc.). That is, it describes the information of an application environment (that is, context); it is an abstract class, and Android provides a concrete implementation class of this abstract class; through it we can get the resources and classes of the application (including application-level operations, such as starting Activity, broadcasting, accepting Intent, etc.). Since the above Context is an abstract class, there must be his implementation class. We can see its subclass through IDE in the source code of Context. Finally, we can get the following figure:
Context.png
The Context class itself is a pure abstract class with two specific implementation subclasses: ContextImpl and ContextWrapper. The ContextWrapper class, as its name suggests, is just a wrapper, the ContextWrapper constructor must contain a real Context reference, and attachBaseContext () is provided in ContextWrapper to specify a real Context object in the ContextWrapper object, and methods that call ContextWrapper will be directed to the real Context object it contains. The ContextThemeWrapper class, as its name suggests, contains an interface related to the Theme, which refers to the theme specified in the AndroidManifest.xml for the Application element or Activity element through android:theme. Of course, only Activity needs a theme, and Service does not need a theme, because Service is a background scene without an interface, so Service directly inherits from ContextWrapper,Application. On the other hand, the ContextImpl class really implements all the functions in Context and the various methods of the Context class called in the application, and their implementation comes from this class. Summary: the two subclasses of Context have a clear division of labor, where ContextImpl is the concrete implementation class of Context and ContextWrapper is the wrapper class of Context. Although Activity,Application,Service inherits from ContextWrapper (Activity inherits from ContextThemeWrapper, a subclass of ContextWrapper), ContextImpl objects are created during their initialization, and ContextImpl implements the methods in Context.
There are several Context in an application
In fact, this question itself does not make any sense, the key lies in the understanding of Context, we can get the answer from the above diagram, the specific implementation subclass of Context in the application is: Activity,Service,Application. Then number of Context = number of Activity + number of Service + 1. Of course, if you are careful enough, there may be questions: we often say that there are four major components, why only Activity,Service holds Context, then Broadcast Receiver,Content Provider? Broadcast Receiver,Content Provider is not a subclass of Context, the Context they hold are passed from other places, so they are not counted in the total number of Context. The above diagram also tells us from another aspect how noble the status of the context class in the whole Android system is, because it is obvious that Activity,Service,Application is its subclass, its status and role is self-evident.
What can Context do?
What exactly can Context do? This is just too much. Context is needed to pop up Toast, start Activity, start Service, send broadcasts, manipulate databases, and so on.
TextView tv = new TextView (getContext ()); ListAdapter adapter = new SimpleCursorAdapter (getApplicationContext (),...); AudioManager am = (AudioManager) getContext (). GetSystemService (Context.AUDIO_SERVICE); getApplicationContext (). GetSharedPreferences (name, mode); getApplicationContext (). GetContentResolver (). Query (uri,...). GetResources (). GetDisplayMetrics (). WidthPixels * 5 / 8; getContext (). StartActivity (intent); getContext (). StartService (intent); getContext (). SendBroadcast (intent)
Context scope
Although Context has great powers, it is not possible to do whatever you want with a random instance of Context, and there are some rules governing its use. Because the concrete instance of Context is implemented by the ContextImpl class, in most scenarios, the three types of Context, Activity, Service, and Application, can be common. However, there are several special scenarios, such as starting Activity and popping up Dialog. For security reasons, Android does not allow Activity or Dialog to appear out of thin air, and the startup of one Activity must be based on another Activity, that is, the return stack formed by it. Dialog must pop up on an Activity (unless it is a Dialog of type System Alert), so in this scenario, we can only use a Context of type Activity, otherwise there will be an error.
Context scope .png
From the figure above, we can see that Context held by Activity has the widest scope and can do anything. Because Activity inherits from ContextThemeWrapper, while Application and Service inherit from ContextWrapper, it is obvious that ContextThemeWrapper has done some operations on the basis of ContextWrapper to make Activity more powerful. Here I will no longer post the source code for everyone's analysis. Interested children's shoes can check the source code themselves. I won't explain too much about YES and NO in the figure above, and here I'll talk about the two uses that Application and Service do not recommend in the figure above.
1: if we use ApplicationContext to launch an Activity with LaunchMode as standard, we will get an error android.util.AndroidRuntimeException: Calling startActivity from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? This is because there is no task stack for a non-Activity type of Context, so the Activity to be started cannot find the stack. The solution to this problem is to specify the FLAG_ACTIVITY_NEW_TASK tag bit for the Activity to be started so that a new task stack is created for it at startup, when the Activity is started in singleTask mode. All this way of starting Activity with Application is not recommended, Service is the same as Application.
2: it is also legal to layout inflate in Application and Service, but the system default theme style is used, and some styles may not be used if you customize them. Therefore, this method is not recommended.
In a word, anything related to UI should be handled with Activity as Context; other operations, such as Service,Activity,Application, can be done. Of course, pay attention to the holding of Context references to prevent memory leaks.
How to get Context
Usually we want to get the Context object, there are four main ways:
1:View.getContext, which returns the Context object of the current View object, usually the Activity object currently being displayed.
2:Activity.getApplicationContext, which gets the Context object of the process in which the current Activity is located. Usually, when we use the Context object, we should give priority to the global process Context.
3:ContextWrapper.getBaseContext (): you can use this method to get a Context before ContextWrapper is decorated, which is not often used in actual development and is not recommended.
4:Activity.this returns the current Activity instance. If it is a UI control, you need to use Activity as the Context object, but the default Toast actually uses ApplicationContext.
GetApplication () and getApplicationContext ()
It is mentioned above that you use getApplicationContext to get the current Application object. I don't know if you think of getApplication (). What's the difference between these two methods? I believe this question will baffle many developers.
GetApplication () & getApplicationContext (). Png
The program will not deceive people, we through the above code, print out that both memory addresses are the same, it seems that they are the same object. In fact, this result is also easy to understand, because as mentioned earlier, Application itself is a Context, so the result of getting getApplicationContext () here is an instance of Application itself. So the question is, since the results of both methods are the same, why should Android provide two methods of duplicating functions?
In fact, there is a big difference between the two methods in scope. The semantics of the getApplication () method is so strong that it is obvious at a glance that it is used to get Application instances, but this method can only be called in Activity and Service. So maybe in most cases we use Application in Activity or Service, but if you want to get an instance of Application in some other scenarios, such as BroadcastReceiver, you can use the getApplicationContext () method.
PublicclassMyReceiverextendsBroadcastReceiver {@ Override publicvoidonReceive (Contextcontext,Intentintent) {ApplicationmyApp= (Application) context.getApplicationContext ();}}
Memory leak caused by Context
However, Context cannot be misused. Poor use may lead to memory leaks. Here are two examples of incorrect referencing methods.
Wrong singleton mode
Public class Singleton {private static Singleton instance; private Context mContext; private Singleton (Context context) {this.mContext = context;} public static Singleton getInstance (Context context) {if (instance = = null) {instance = new Singleton (context);} return instance;}}
This is a non-thread-safe singleton mode, instance as a static object, its life cycle is longer than ordinary objects, which also contains Activity, if Activity A to getInstance to get the instance object, input this, memory-resident Singleton to save your incoming Activity An object, and always hold, even if the Activity is destroyed, but because its reference still exists in a Singleton, it can not be GC, resulting in a memory leak.
View holds Activity references
Public class MainActivity extends Activity {private static Drawable mDrawable; @ Override protected void onCreate (Bundle saveInstanceState) {super.onCreate (saveInstanceState); setContentView (R.layout.activity_main); ImageView iv = new ImageView (this); mDrawable = getResources () .getDrawable (R.drawable.ic_launcher); iv.setImageDrawable (mDrawable);}}
There is a static Drawable object when ImageView sets this Drawable, ImageView holds the reference to mDrawable, and the this passed in by ImageView is the mContext of MainActivity, because the mDrawable modified by static is resident in memory, MainActivity is its indirect reference, and when MainActivity is destroyed, it cannot be dropped by GC, resulting in a memory leak.
Correct use of Context
Generally speaking, the memory leak caused by Context is almost always when Context is destroyed, but it fails because it is referenced, and the Context object of Application can be understood to exist with the process, so we summarize the correct posture for using Context:
1: when the Context of Application can handle, and the life cycle of the object is long, the priority is to use Context of Application.
2: don't let objects whose life cycle is longer than Activity hold references to Activity.
3: try not to use non-static inner classes in Activity, because non-static inner classes implicitly hold references to external class instances. If static inner classes are used, external instance references are held as weak references.
Thank you for your reading, the above is the content of "what is Context", after the study of this article, I believe you have a deeper understanding of what Context is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.