Sobes.tech
Junior — Middle

Can you give an example of using local contexts in programs?

sobes.tech AI

Answer from AI

Local contexts in Android are objects of type Context associated with a specific application component, such as an Activity or Service. They are used to access resources, system services, and to create UI.

An example of using a local context is creating a Toast message within an Activity:

class MainActivity : AppCompatActivity() {
    fun showMessage() {
        Toast.makeText(this, "Hello, local context!", Toast.LENGTH_SHORT).show()
    }
}

Here, this is the local context of the Activity, which provides access to resources and allows the message to be displayed correctly.

Using a local context is important to avoid memory leaks, for example, you should not pass the Activity context to long-lived objects; instead, use the application context if necessary.