SoFunction
Updated on 2025-03-11

Detailed explanation of how to use Context in Android

Detailed explanation of how to use Context in Android

summary:

Context literally means context, located in the framework package. In fact, this class is LONG type, similar to the Handle handle in Win32. Many methods need to use Context to identify the caller's instance: for example, the first parameter of Toast is Context. Generally, we use this directly instead in Activity. The instance representing the caller is Activity. When we use this, we will report an error when using this, so we may use it to solve it. The main reason is that the classes that implement Context mainly include several Android-specific models, Activity and Service.

Context provides an interface for global information about the application environment. It is an abstract class whose execution is provided by the Android system. It allows to obtain resources and types characterized by applications. At the same time, start application-level operations, such as launching Activity, broadcasting and receiving intents.

The following are some get methods of Context, through which the global information of the application environment can be obtained:

 abstract Context getApplicationContext ()
Return the context of the single, global Application object of the current process.

 abstract ApplicationInfo getApplicationInfo ()
Return the full application info for this context's package.

 abstract ContentResolver getContentResolver ()
Return a ContentResolver instance for your application's package.

 abstract PackageManager getPackageManager ()
Return PackageManager instance to find global package information.

 abstract String getPackageName ()
Return the name of this application's package.

 abstract Resources getResources ()
Return a Resources instance for your application's package.

 abstract SharedPreferences getSharedPreferences (String name, int mode)
Retrieve and hold the contents of the preferences file 'name', returning a SharedPreferences through which you can retrieve and modify its values. Only one instance of the SharedPreferences object is returned to any callers for the same name, meaning they will see each other's edits as soon as they are made.

 final String getString (int resId)
Return a localized string from the application's package's default string table.

 abstract Object getSystemService (String name)
Return the handle to a system-level service by name. The class of the returned object varies by the requested name. Currently available names are:

There are many useful methods, and we will not list them one by one. Please refer to the documentation for details, Context is very useful anyway.

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!