Readily available Application objects and application objects
In Android development, Application and Context objects should be the objects we have the most contact with, especially Context objects.
When we are in an Activity or Service, because they are sub-classes of Context, "this" can be equivalent to the use of Context objects. However, in many cases, this Context is not so readily available. Consider the following:
- You need to use the Context SDK. To use the SDK, you need to add the Context transfer code;
- If you need to use Context, you need to modify the original logic and pass the Context;
- After being injected into the Java environment, Context is required to access various IPC services;
- And so on.
Therefore, if you can find a way to obtain the Application object of the current process without touching the original logic, the above mentioned problems can be solved. This is a bit abstract. For example, when we write a custom Application class, we usually add a static method getContext (or other similar names) as follows:
class final MyApplication extends Application{ private static Application sInstance; @Override public void onCreate(){ sInstance = this; } public static Application getContext(){ return sInstance; } //... //...}
This code is easy to understand. It is mainly used when Context is used later. Because the Application is global, internal leakage can be prevented. But how can I get this Application object even if no custom Application is available?
In fact, this time there are not many dry goods. Here I provide a method that can be compatible with 1.6 to 5.1 (later firmware should also be compatible ).
The static fields of the system class are obtained through reflection. The process is as follows:
- Obtain the static mApplicationObject field through the RuntimeInit class. The field type is android. app. ActivityThread $ ApplicationThread;
- Obtain the this $0 field through the ApplicationThread class. Note that this field is generated by the compiler. The type of this field is android. app. ActivityThread;
- Obtain the mInitialApplication field of the ActivityThread class. This field is the Application object;
Because reflection calls are involved, the complete code is not written. Write a simple pseudo code.
Applicatioin app = RuntimeInit.mApplicationObject.this$0.mInitialApplication;
Certainly, this is not the only method. Please share it with us.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.