The main function is to load and access resources (context is usually used to get app resources, create UI, get system service service, start activity, bind service, send broadcast, get app info, etc.)
How to Understand:
- We can understand it as "context": it runs through the application;
- Can also be understood as "operating environment": it provides an application to run the necessary information, resources, system services, etc.;
- The same can be understood as a "scene": User action and system interaction this process is a scenario, such as the switch between the activity, service startup and so on the context.
Context Instance creation:
- When you create a Application object, and the entire app has a application object
- When you create a service object
- When you create an Activity object
Context-dependent class inheritance relationships:
There are two kinds of context in Android, one is application context, the other is activity context, and usually we pass the activity context between various classes and methods.
For example, an activity oncreate:
protected void onCreate (Bundle state) { super.oncreate (state); New TextView (this// Pass context to view Control label.settext ("Leaks is bad "); Setcontentview (label);}
Passing the activity context to view means that view has a reference to activity that references the resources that the activity occupies: view hierachy, Resource, and so on. This will leak a lot of memory if the context has a memory leak. The leak here means that the GC has no way to reclaim the activity's memory.
Leaking an entire activity is a very easy thing to do.
When the screen rotates, the system destroys the current activity, saves the state information, and then creates a new one.
To avoid context-related memory leaks, note the following points:
- Do not allow objects with long life cycles to refer to the activity context, that is, to ensure that the object referencing the activity is the same as the activity itself life cycle
- For objects with long life cycles, you can use the application context
- Avoid non-static inner classes, use static classes as much as possible, avoid life cycle problems, and notice life-cycle changes caused by internal classes to external object references
Context in Android