user130532
user130532

Reputation:

How to obtain application context from broadcast receiver?

I have an extension of the Application class that I need to obtain reference in a BroadcastReceiver I have created. The context passed into the "onReceive" is a restricted context. Is there a way to obtain reference to the actual application context?

Upvotes: 15

Views: 15417

Answers (3)

sagarkothari
sagarkothari

Reputation: 24810

class SMSReceiver: BroadcastReceiver() {
    @RequiresApi(Build.VERSION_CODES.O)
    override fun onReceive(context: Context?, intent: Intent?) {
        val smsIntent = intent ?: return
        val appContext = context?.applicationContext ?: return
        // Do something here.
    }
}

Upvotes: 0

knninjutsu
knninjutsu

Reputation: 45

BroadcastReceiver already gives the context. Look at the onReceive.

public void onReceive(Context context, Intent intent)

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006664

Call getApplicationContext() on the Context supplied to you in onReceive(), just as you would call getApplicationContext() on an Activity.

I have an extension of the Application that allows me to non-statically obtain reference to several objects I need.

While syntactically Application is not static, it has the same impact, particularly with respect to memory leaks.

Upvotes: 29

Related Questions