Posted on

Android Context


Android Context
Designed by Freepik

Hey, you have been using Android Context since the first day. It’s never been an issue and that’s why getting deep into this might not been a necessity. But at some point you starting to feel more confident in Android and can ask questions for gaps that you have. If so, and you want learn more about Context purpose, then let’s get started!

Purpose

There’re many usages of Context class. You might not even consider how many important methods come from Context. The primary is accessing resources from res directory and files on a disk. Then there’s starting a Service, broadcasting, even starting new Activity is a Context method and Toast as well!

Types

There’s two types: Activity and Application Context. The second one is static singleton which lives during the app’s live. Activity ones are being destroyed after each activity. So if you have some background networking, then better use application context or activity one can be destroyed and you get null pointer when accessing it.

Getting Resources

Each time you want to get a string, dimension, theme you use it through a context instance. And since Activities and Fragments extend Context, it’s so subtle. Right, you wouldn’t be able to access all of it if you don’t have a context instance. Fortunately, Android framework provides it to you anywhere you need, like in BroadcastReceviers via intent.

So what makes this Context so magical and irreplaceable, right? AssetManager┬áhandles all this resource stuff, context has an instance of it. And it doesn’t have many public methods. getString public method leads to a native implementation.

Why Toast?

Toast doesn’t extend a view, which means it doesn’t need a context in constructor, but there’s one method which you should take a look at. It takes resource id of a string and as we know we need an asset manager from a context which returns localized string for us. And of course to access package information.

 

One thing for sure, Context is a huge part of the Android platform framework which wraps lots of app related functionality.