current position:Home>Context didn't understand why he got a high salary?, Nginxfair principle

Context didn't understand why he got a high salary?, Nginxfair principle

2022-01-27 02:33:12 Alibaba_ Open Source

In the source Context

/**

  • 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 are explained in this way Context Of :Context Provides an interface for global information about the application environment . It's an abstract class , Its execution is Android Provided by the system . It allows the acquisition of resources and types characterized by applications , Is a leader of some resources ( Application environment variables, etc ) The context of . That is to say , It describes information about an application environment ( That is context ); Is an abstract class ,Android The concrete implementation class of the abstract class is provided ; Through it we can get the resources and classes of the application ( Including application level operations , If you start Activity, Broadcast , Accept Intent etc. ). Since it's up there Context Is an abstract class , Then there must be his implementation class , We are Context In the source code of IDE You can view its subclasses and finally get the following diagram :

Context The class itself is a pure abstract class , It has two concrete implementation subclasses :ContextImpl and ContextWrapper. among ContextWrapper class , As the name says , It's just a package ,ContextWrapper The constructor must contain a real Context quote , meanwhile ContextWrapper Provided in attachBaseContext() For giving ContextWrapper Object to specify the real Context object , call ContextWrapper All methods will be turned to the real Context object .ContextThemeWrapper class , As the name says , It contains the theme (Theme) Associated interface , The theme here refers to AndroidManifest.xml Pass through android:theme by Application Element or Activity The theme specified by the element . Of course , Only Activity We need the theme ,Service It doesn't need a theme , because Service It is a background scene without interface , therefore Service Directly inherited from ContextWrapper,Application Empathy . and ContextImpl Class actually implements Context All functions in , Various functions called in the application Context Class method , Its implementation comes from this kind of . One sentence summary :Context The division of labor between the two subclasses is clear , among ContextImpl yes Context Implementation class of ,ContextWrapper yes Context The wrapper class .Activity,Application,Service Although all inherited from ContextWrapper(Activity Inherited from ContextWrapper Subclasses of ContextThemeWrapper), But they are created during initialization ContextImpl object , from ContextImpl Realization Context The method in .

An application has several Context

In fact, this question itself has no meaning , The key is to Context The understanding of the , From the diagram above, we can get the answer , In the application Context The concrete implementation subclass of is :Activity,Service,Application. that Context Number =Activity Number +Service Number +1. Of course, if you are careful enough , There may be questions : We often say four components , Why is there only Activity,Service hold Context, that Broadcast Receiver,Content Provider Well ?Broadcast Receiver,Content Provider Not at all Context Subclasses of , What they hold Context It's all passed down from other places , So it doesn't count Context total . The above diagram also tells us from another side Context Class in the whole Android How noble the position in the system is , Because obviously Activity,Service,Application They are all subclasses , Its status and role are self-evident .

Context Can do

Context What functions can be realized ? This is too much , eject Toast、 start-up Activity、 start-up Service、 Send a broadcast 、 Operating the database and so on all need to use Context.

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

getContext().getResources().getDisplayMetrics().widthPixels * 5 / 8;

getContext().startActivity(intent);

getContext().startService(intent);

getContext().sendBroadcast(intent);

《 A big factory Java Analysis of interview questions + Back end development learning notes + The latest architecture explanation video + Practical project source code handout 》

【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 Full content open source sharing

Context Scope

although Context have great magic power , But you don't just get one Context Instance can do whatever you want , Its use is still limited by some rules . because Context The specific example of is by ContextImpl Class to implement , So in most scenarios ,Activity、Service and Application These three types of Context They can be used in general . But there are several special scenes , For example, start. Activity, And pop up Dialog. For safety reasons ,Android It's not allowed Activity or Dialog Out of thin air , One Activity The start of must be established in another Activity Based on , That is to say, the return stack formed by this . and Dialog Must be in a Activity Pop up above ( Unless it is System Alert Type of Dialog), So in this scenario , We can only use Activity Type of Context, Otherwise, there will be mistakes .

image

From the picture above, we can see that Activity Held by Context Has the widest scope , omnipotent . because Activity Inherited from ContextThemeWrapper, and Application and Service Inherited from ContextWrapper, Obviously ContextThemeWrapper stay ContextWrapper On the basis of, some operations are done to make Activity Become stronger , Here I will not post the source code for your analysis , Interested children's shoes can check the source code . In the picture above YES and NO I won't explain too much anymore , Here, let me talk about the picture above Application and Service Two use cases that are not recommended .

1: If we use ApplicationContext Go start a LaunchMode by standard Of Activity I will make a mistake android.util.AndroidRuntimeException: Calling startActivity from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want? It's because it's not Activity Type of Context There is no so-called task stack , So the to be started Activity You can't find the stack . The way to solve this problem is to start Activity Appoint FLAG_ACTIVITY_NEW_TASK Marker bit , In this way, a new task stack is created for it when it starts , And then Activity In order to singleTask Mode enabled . All this is used Application start-up Activity The method of... Is not recommended ,Service Same as Application.

2: stay Application and Service In the middle layout inflate It's also legal , But it will use the default theme style of the system , If you customize some styles, they may not be used . Therefore, this method is not recommended .

One sentence summary : Always follow UI dependent , Should be used Activity As Context To deal with it ; Other operations ,Service,Activity,Application And so on , Yes, of course , Be careful Context Referenced holding , Prevent memory leaks .

How to get Context

Usually we want to get Context object , There are four main methods

1:View.getContext, Returns the current View Object's Context object , Usually what is currently being displayed Activity object .

2:Activity.getApplicationContext, Get current Activity Where ( application ) Process Context object , Usually we use Context Object time , Give priority to this overall process Context.

3:ContextWrapper.getBaseContext(): To get a ContextWrapper Before decorating Context, You can use this method , This method is not used much in practical development , Not recommended .

4:Activity.this Returns the current Activity example , If it is UI Control needs to use Activity As Context object , But by default Toast Actually use ApplicationContext It's fine too .

getApplication() and getApplicationContext()

It's about getting the current Application Object use getApplicationContext, I wonder if you think of getApplication(), What's the difference between the two methods ? I believe this problem will embarrass many developers .

The program won't lie , We use the above code , Print out that the memory addresses of both are the same , Looks like they're the same thing . In fact, the result is very understandable , Because I've already said that ,Application Is itself a Context, So here we get getApplicationContext() The result is Application An example of itself . So here comes the question , Since the results of the two methods are the same , that Android Why provide two ways to repeat functions ? In fact, the two methods are quite different in scope .getApplication() The semantics of the method is very strong , You know it's for getting Application Example of , But this method only works in Activity and Service Can be called to . So maybe in most cases we're Activity perhaps Service Use in Application Of , But in some other scenarios , such as BroadcastReceiver China also wants to get Application Example , You can use getApplicationContext() The method .

publicclassMyReceiverextendsBroadcastReceiver{

@Override

publicvoidonReceive(Contextcontext,Intentintent){

ApplicationmyApp=(Application)context.getApplicationContext();

}

}

Context Cause memory leaks

but Context You can't use it casually , Bad use may cause memory leakage , Here are two examples of incorrect references .

Wrong singleton pattern

public class Singleton {

private static Singleton instance;

private Context mContext;

copyright notice
author[Alibaba_ Open Source],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270233101297.html