English | Site Directory

Android - An Open Handset Alliance Project

android.content
public abstract class

android.content.Context

java.lang.Object
android.content.Context

Interface to global information about an application environment. This is an abstract class whose implementation is provided by ApplicationContext. 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.

Known Direct Subclasses
Known Indirect Subclasses

Summary

Constants

      Value  
String  ACTIVITY_SERVICE  Use with getSystemService(String) to retrieve a ActivityManager for interacting with the global system state.  "activity" 
String  ALARM_SERVICE  Use with getSystemService(String) to retrieve a AlarmManager for receiving intents at a time of your choosing.  "alarm" 
int  BIND_AUTO_CREATE  Flag for bindService(Intent, ServiceConnection, int): automatically create the service as long as the binding exists.  0x00000001 
int  BIND_DEBUG_UNBIND  Flag for bindService(Intent, ServiceConnection, int): include debugging help for mismatched calls to unbind.  0x00000002 
int  CONTEXT_IGNORE_SECURITY  Flag for use with createPackageContext(String, int): ignore any security restrictions on the Context being requested, allowing it to always be loaded.  0x00000002 
int  CONTEXT_INCLUDE_CODE  Flag for use with createPackageContext(String, int): include the application code with the context.  0x00000001 
String  INFLATE_SERVICE  Use with getSystemService(String) to retrieve a ViewInflate for inflating layout resources in this context.  "inflate" 
String  KEYGUARD_SERVICE  Use with getSystemService(String) to retrieve a NotificationManager for controlling keyguard.  "keyguard" 
String  LOCATION_SERVICE  Use with getSystemService(String) to retrieve a LocationManager for controlling location updates.  "location" 
int  MODE_APPEND  File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.  32768  0x00008000 
int  MODE_PRIVATE  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).  0x00000000 
int  MODE_WORLD_READABLE  File creation mode: allow all other applications to have read access to the created file.  0x00000001 
int  MODE_WORLD_WRITEABLE  File creation mode: allow all other applications to have write access to the created file.  0x00000002 
String  NOTIFICATION_SERVICE  Use with getSystemService(String) to retrieve a NotificationManager for informing the user of background events.  "notification" 
String  POWER_SERVICE  Use with getSystemService(String) to retrieve a PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.  "power" 
String  SEARCH_SERVICE  Use with getSystemService(String) to retrieve a SearchManager for handling searches.  "search" 
String  WINDOW_SERVICE  Use with getSystemService(String) to retrieve a ViewManager for accessing the system's window manager.  "window" 

Public Constructors

          Context()

Public Methods

abstract        boolean  bindService(Intent service, ServiceConnection conn, int flags)
Connect to an application service, creating it if needed.
abstract        void  broadcastIntent(Intent intent, String receiverPermission)
Broadcast the given intent to all interested IntentReceivers, allowing an optional required permission to be enforced.
abstract        void  broadcastIntent(Intent intent, String receiverPermission, IntentReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)
Version of broadcastIntent(Intent) that allows you to receive data back from the broadcast.
abstract        void  broadcastIntent(Intent intent)
Broadcast the given intent to all interested IntentReceivers.
abstract        void  broadcastIntentSerialized(Intent intent, String receiverPermission)
Broadcast the given intent to all interested IntentReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers.
abstract        void  broadcastStickyIntent(Intent intent)
Perform a broadcastIntent(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(IntentReceiver, IntentFilter).
abstract        int  checkCallingOrSelfPermission(String permission)
Determine whether the calling process of an IPC or you have been granted a particular permission.
abstract        int  checkCallingPermission(String permission)
Determine whether the calling process of an IPC you are handling has been granted a particular permission.
abstract        int  checkPermission(String permission, int pid, int uid)
Determine whether the given permission is allowed for a particular process and user ID running in the system.
abstract        void  clearWallpaper()
Remove any currently set wallpaper, reverting to the system's default wallpaper.
abstract        SQLiteDatabase  createDatabase(String name, int version, int mode, CursorFactory factory)
Create a new private SQLiteDatabase associate with this Context's application package.
abstract        Context  createPackageContext(String packageName, int flags)
Return a new Context object for the given application name.
abstract        boolean  deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.
abstract        boolean  deleteFile(String name)
Delete the given private file associated with this Context's application package.
abstract        String[]  fileList()
Returns an array of strings naming the private files associated with this Context's application package.
abstract        AssetManager  getAssets()
Return an AssetManager instance for your application's package.
abstract        ClassLoader  getClassLoader()
Return a class loader you can use to retrieve classes in this package.
abstract        ContentResolver  getContentResolver()
Return a ContentResolver instance for your application's package.
abstract        File  getDatabasePath(String name)
Returns the absolute path on the filesystem where a database created with createDatabase(String, int, int, SQLiteDatabase.CursorFactory) is stored.
abstract        File  getDir(String name, int mode)
Retrieve, creating if needed, a new directly in which the application can place its own custom data files.
abstract        File  getFileStreamPath(String name)
Returns the absolute path on the filesystem where a file created with openFileOutput(String, int) is stored.
abstract        File  getFilesDir()
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
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.
    final    String  getString(int resId, Object[] formatArgs)
Return a localized formatted string from the application's package's default string table, substituting the format arguments as defined in Formatter and format(String, Object...).
    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.
    final    CharSequence  getText(int resId)
Return a localized, styled CharSequence from the application's package's default string table.
abstract        Theme  getTheme()
Return the Theme object associated with this Context.
abstract        Drawable  getWallpaper()
Like peekWallpaper(), but always returns a valid Drawable.
    final    StyledAttributes  obtainStyledAttributes(int resid, int[] attrs)
Retrieve styled attribute information in this Context's theme.
    final    StyledAttributes  obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
Retrieve styled attribute information in this Context's theme.
    final    StyledAttributes  obtainStyledAttributes(int[] attrs)
Retrieve styled attribute information in this Context's theme.
    final    StyledAttributes  obtainStyledAttributes(AttributeSet set, int[] attrs)
Retrieve styled attribute information in this Context's theme.
abstract        SQLiteDatabase  openDatabase(String file, CursorFactory factory)
Open an existing private SQLiteDatabase associated with this Context's application package.
abstract        FileInputStream  openFileInput(String name)
Open a private file associated with this Context's application package for reading.
abstract        FileOutputStream  openFileOutput(String name, int mode)
Open a private file associated with this Context's application package for writing.
abstract        Drawable  peekWallpaper()
Retrieve the current system wallpaper.
abstract        Intent  registerReceiver(IntentReceiver receiver, IntentFilter filter)
Register an IntentReceiver to be run in the main activity thread.
abstract        Intent  registerReceiver(IntentReceiver receiver, IntentFilter filter, String broadcastPermission, Handler scheduler)
Register to receive intent broadcasts, to run in the context of scheduler.
abstract        void  setTheme(int resid)
Set the base theme for this context.
abstract        void  setThreadPriority(int threadId, int priority)
Change the priority of a thread running in your process.
abstract        void  setWallpaper(InputStream data)
Change the current system wallpaper to a specific byte stream.
abstract        void  setWallpaper(Bitmap bitmap)
Change the current system wallpaper to a bitmap.
abstract        DialogInterface  showAlert(CharSequence title, int iconId, CharSequence message, CharSequence button1Text, OnClickListener button1Listener, CharSequence button2Text, OnClickListener button2Listener, CharSequence button3Text, OnClickListener button3Listener, boolean cancelable, OnCancelListener cancelListener)
Display a simple, non-blocking two button alert dialog.
abstract        DialogInterface  showAlert(CharSequence title, CharSequence message, CharSequence button1Text, Message button1Callback, CharSequence button2Text, Message button2Callback, boolean cancelable, Message cancelCallback)
This method is deprecated. use showAlert(CharSequence, int, CharSequence, CharSequence, DialogInterface.OnClickListener, CharSequence, DialogInterface.OnClickListener, boolean, DialogInterface.OnCancelListener)
abstract        DialogInterface  showAlert(CharSequence title, int iconId, CharSequence message, CharSequence button1Text, OnClickListener button1Listener, CharSequence button2Text, OnClickListener button2Listener, boolean cancelable, OnCancelListener cancelListener)
Display a simple, non-blocking two button alert dialog.
abstract        DialogInterface  showAlert(CharSequence title, int iconId, CharSequence message, CharSequence buttonText, boolean cancelable)
Display a simple, non-blocking one button alert dialog.
abstract        DialogInterface  showAlert(CharSequence title, int iconId, CharSequence message, CharSequence buttonText, OnClickListener buttonListener, boolean cancelable, OnCancelListener cancelListener)
Display a simple, non-blocking one button alert dialog.
abstract        void  startActivity(Intent intent)
Launch a new activity.
abstract        boolean  startInstrumentation(ComponentName className, String profileFile, Bundle arguments)
Start executing an Instrumentation class.
abstract        ComponentName  startService(Intent service, Bundle args)
Request that a given application service be started.
abstract        boolean  stopService(Intent service)
Request that a given application service be stopped.
abstract        void  unbindService(ServiceConnection conn)
Disconnect from an application service.
abstract        void  unbroadcastStickyIntent(Intent intent)
Remove the data previously sent with broadcastStickyIntent(Intent), so that it is as if the sticky broadcast had never happened.
abstract        void  unregisterReceiver(IntentReceiver receiver)
Unregister a previously registered IntentReceiver.
Methods inherited from class java.lang.Object

Details

Constants

public static final String ACTIVITY_SERVICE

Use with getSystemService(String) to retrieve a ActivityManager for interacting with the global system state.
Constant Value: "activity"

public static final String ALARM_SERVICE

Use with getSystemService(String) to retrieve a AlarmManager for receiving intents at a time of your choosing.
Constant Value: "alarm"

public static final int BIND_AUTO_CREATE

Flag for bindService(Intent, ServiceConnection, int): automatically create the service as long as the binding exists. Note that while this will create the service, its onStart(int, Bundle) method will still only be called due to an explicit call to startService(Intent, Bundle). Even without that, though, this still provides you with access to the service object while the service is created.

Specifying this flag also tells the system to treat the service as being as important as your own process -- that is, when deciding which process should be killed to free memory, the service will only be considered a candidate as long as the processes of any such bindings is also a candidate to be killed. This is to avoid situations where the service is being continually created and killed due to low memory.

Constant Value: 1 (0x00000001)

public static final int BIND_DEBUG_UNBIND

Flag for bindService(Intent, ServiceConnection, int): include debugging help for mismatched calls to unbind. When this flag is set, the callstack of the following unbindService(ServiceConnection) call is retained, to be printed if a later incorrect unbind call is made. Note that doing this requires retaining information about the binding that was made for the lifetime of the app, resulting in a leak -- this should only be used for debugging.
Constant Value: 2 (0x00000002)

public static final int CONTEXT_IGNORE_SECURITY

Flag for use with createPackageContext(String, int): ignore any security restrictions on the Context being requested, allowing it to always be loaded. For use with CONTEXT_INCLUDE_CODE to allow code to be loaded into a process even when it isn't safe to do so. Use with extreme care!
Constant Value: 2 (0x00000002)

public static final int CONTEXT_INCLUDE_CODE

Flag for use with createPackageContext(String, int): include the application code with the context. This means loading code into the caller's process, so that getClassLoader() can be used to instantiate the application's classes. Setting this flags imposes security restrictions on what application context you can access; if the requested application can not be safely loaded into your process, java.lang.SecurityException will be thrown. If this flag is not set, there will be no restrictions on the packages that can be loaded, but getClassLoader() will always return the default system class loader.
Constant Value: 1 (0x00000001)

public static final String INFLATE_SERVICE

Use with getSystemService(String) to retrieve a ViewInflate for inflating layout resources in this context.
Constant Value: "inflate"

public static final String KEYGUARD_SERVICE

Use with getSystemService(String) to retrieve a NotificationManager for controlling keyguard.
Constant Value: "keyguard"

public static final String LOCATION_SERVICE

Use with getSystemService(String) to retrieve a LocationManager for controlling location updates.
Constant Value: "location"

public static final int MODE_APPEND

File creation mode: for use with openFileOutput(String, int), if the file already exists then write data to the end of the existing file instead of erasing it.
Constant Value: 32768 (0x00008000)

public static final int MODE_PRIVATE

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).
Constant Value: 0 (0x00000000)

public static final int MODE_WORLD_READABLE

File creation mode: allow all other applications to have read access to the created file.
Constant Value: 1 (0x00000001)

public static final int MODE_WORLD_WRITEABLE

File creation mode: allow all other applications to have write access to the created file.
Constant Value: 2 (0x00000002)

public static final String NOTIFICATION_SERVICE

Use with getSystemService(String) to retrieve a NotificationManager for informing the user of background events.
Constant Value: "notification"

public static final String POWER_SERVICE

Use with getSystemService(String) to retrieve a PowerManager for controlling power management, including "wake locks," which let you keep the device on while you're running long tasks.
Constant Value: "power"

public static final String SEARCH_SERVICE

Use with getSystemService(String) to retrieve a SearchManager for handling searches.
Constant Value: "search"

public static final String WINDOW_SERVICE

Use with getSystemService(String) to retrieve a ViewManager for accessing the system's window manager.
Constant Value: "window"

Public Constructors

public Context()

Public Methods

public abstract boolean bindService(Intent service, ServiceConnection conn, int flags)

Connect to an application service, creating it if needed. This defines a dependency between your application and the service. The given conn will receive the service object when its created and be told if it dies and restarts. The service will be considered required by the system only for as long as the calling context exists. For example, if this Context is an Activity that is stopped, the service will not be required to continue running until the Activity is resumed.

This function will throw SecurityException if you do not have permission to bind to the given service.

Note: this method can not be called from an IntentReceiver component. A pattern you can use to communicate from an IntentReceiver to a Service is to call startService(Intent, Bundle) with the arguments containing the command to be sent, with the service calling its stopSelf(int) method when done executing that command. See the API demo App/Service/Service Start Arguments Controller for an illustration of this. It is okay, however, to use this method from an IntentReceiver that has been registered with registerReceiver(IntentReceiver, IntentFilter), since the lifetime of this IntentReceiver is tied to another object (the one that registered it).

Parameters

service Identifies the service to connect to. The Intent may specify either an explicit component name, or a logical description (action, category, etc) to match an IntentFilter published by a service.
conn Receives information as the service is started and stopped.
flags Operation options for the binding. May be 0 or BIND_AUTO_CREATE.

Returns

  • If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.

Throws

SecurityException

public abstract void broadcastIntent(Intent intent, String receiverPermission)

Broadcast the given intent to all interested IntentReceivers, allowing an optional required permission to be enforced. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See IntentReceiver for more information on Intent broadcasts.

Parameters

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission (optional) String naming a permissions that a receiver must hold in order to receive your broadcast. If null, no permission is required.

public abstract void broadcastIntent(Intent intent, String receiverPermission, IntentReceiver resultReceiver, Handler scheduler, int initialCode, String initialData, Bundle initialExtras)

Version of broadcastIntent(Intent) that allows you to receive data back from the broadcast. This is accomplished by supplying your own IntentReceiver when calling, which will be treated as a final receiver at the end of the broadcast -- its onReceiveIntent(Context, Intent) method will be called with the result values collected from the other receivers. If you use an resultReceiver with this method, then the broadcast will be serialized in the same way as calling broadcastIntentSerialized(Intent, String).

Like broadcastIntent(Intent), this method is asynchronous; it will return before resultReceiver.onReceiveIntent() is called.

See IntentReceiver for more information on Intent broadcasts.

Parameters

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission String naming a permissions that a receiver must hold in order to receive your broadcast. If null, no permission is required.
resultReceiver Your own IntentReceiver to treat as the final receiver of the broadcast.
scheduler A custom Handler with which to schedule the resultReceiver callback; if null it will be scheduled in the Context's main thread.
initialCode An initial value for the result code. Often Activity.RESULT_OK.
initialData An initial value for the result data. Often null.
initialExtras An initial value for the result extras. Often null.

public abstract void broadcastIntent(Intent intent)

Broadcast the given intent to all interested IntentReceivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See IntentReceiver for more information on Intent broadcasts.

Parameters

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.

public abstract void broadcastIntentSerialized(Intent intent, String receiverPermission)

Broadcast the given intent to all interested IntentReceivers, delivering them one at a time to allow more preferred receivers to consume the broadcast before it is delivered to less preferred receivers. This call is asynchronous; it returns immediately, and you will continue executing while the receivers are run.

See IntentReceiver for more information on Intent broadcasts.

Parameters

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast.
receiverPermission (optional) String naming a permissions that a receiver must hold in order to receive your broadcast. If null, no permission is required.

public abstract void broadcastStickyIntent(Intent intent)

Perform a broadcastIntent(Intent) that is "sticky," meaning the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(IntentReceiver, IntentFilter). In all other ways, this behaves the same as broadcastIntent(Intent).

You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission, SecurityException will be thrown.

Parameters

intent The Intent to broadcast; all receivers matching this Intent will receive the broadcast, and the Intent will be held to be re-broadcast to future receivers.

public abstract int checkCallingOrSelfPermission(String permission)

Determine whether the calling process of an IPC or you have been granted a particular permission. This is the same as checkCallingPermission(String), except it grants your own permissions if you are not currently processing an IPC. Use with care!

Parameters

permission The name of the permission being checked.

Returns

public abstract int checkCallingPermission(String permission)

Determine whether the calling process of an IPC you are handling has been granted a particular permission. This is basically the same use calling checkPermission(String, int, int) with the pid and uid returned by getCallingPid() and getCallingUid(). One important difference is that if you are not currently processing an IPC, this function will always fail. This is done to protect against accidentally leaking permissions; you can use checkCallingOrSelfPermission(String) to avoid this protection.

Parameters

permission The name of the permission being checked.

Returns

public abstract int checkPermission(String permission, int pid, int uid)

Determine whether the given permission is allowed for a particular process and user ID running in the system.

Parameters

permission The name of the permission being checked.
pid The process ID being checked against. Must be > 0.
uid The user ID being checked against. A uid of 0 is the root user, which will pass every permission check.

Returns

public abstract void clearWallpaper()

Remove any currently set wallpaper, reverting to the system's default wallpaper.

public abstract SQLiteDatabase createDatabase(String name, int version, int mode, CursorFactory factory)

Create a new private SQLiteDatabase associate with this Context's application package. Throws FileNotFoundException if the databse could not be created.

Parameters

name The name (unique in the application package) of the database.
version A version number to tag the database with.
mode