Key Context Features

Many things take a Context. Constructors for all of our widgets and containers, for example, take a Context as a parameter.

In terms of directly calling functions on a Context, though, there are a few categories into which those functions fall.

Access to Resources and Assets

If you want to get the value or otherwise use a resource, you will wind up using a Context.

Sometimes, that comes from passing the Context to something else as a parameter. We will see examples of that later in the book, such as data binding.

Sometimes, that comes from calling convenience functions on Context itself, such as getString().

In general, though, access to resources comes from a Resources object, and you get one of those by calling getResources() on a Context. Resources has functions to retrieve most types of resources: strings, dimensions, colors, and so on. The convenience functions on Context simply delegate to the Resources object — for example, getString() on Context just forwards your request to getString() on Resources.

In addition to resources, an Android app can also have assets, found in an assets/ directory that sits alongside directories like src/ and res/. If you package assets this way with your app, calling getAssets() on a Context gives you an AssetManager. From there, you can work with the assets, such as by calling open() to get an InputStream from which you can read an asset’s content.

Access to Key Directories

Resources and assets are packaged with the app. Beyond those, we have the ability to write to files on the local filesystem and read them back later. On the whole, this is standard I/O using Java classes like File, InputStream, OutputWriter, and so on. The big limitation is where we can read and write.

For that, Context has a family of functions, like getFilesDir(), that return File objects representing directories that we can read from and (usually) write to. We will explore those functions in detail later in the book.

Access to System Services

Lots of stuff used by your app is actually managed outside of your app.

For example, suppose that you want to find out the device’s location. Your app code does not work with GPS hardware directly. Instead, it will work with a LocationManager or something that wraps around a LocationManager. LocationManager is a “system service”, and it in turn will talk to other parts of the OS that, eventually, work with the GPS hardware.

Whenever you need access to a “system service”, the typical approach to get one is to call getSystemService() on a Context. Occasionally, there will be other approaches:

Access to Other Components

As we start to explore Android’s components more, you will see that if we want to work with other components from an existing component, we will need a Context.

Specifically, we use a Context to:


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.