Android - Getting context from a Broadcast receiver onReceive() to send to

44,681

Solution 1

public abstract void onReceive(Context context, Intent intent)

onReceive gives you the context. What more do you want?

Solution 2

Well the Answer mentioned above is not of any use. You can use the context as long as you are in onReceive. once you code has returned from onReceive, the context is no longer existing.

So your problem statement say you wanted to start the service using this context in your intent creation and then calling startService with this context object. That cannot be done.

Read this what can and cannot be done in BroadcastReceiver context.

http://developer.android.com/reference/android/content/BroadcastReceiver.html

Solution 3

In the BroadcastReceiver the

onReceive(Context context, Intent intent)

method provides context

so

to start activity use

context.startActivity(intent);

and to start service use

context.startService(intent);
Share:
44,681
madu
Author by

madu

Updated on July 08, 2022

Comments

  • madu
    madu almost 2 years

    I basically want to make an intent and pass it to a service from my BroadcastReceiver's onReceive().

    So far I always used View.getContext(), but here, I'm stuck. How exactly can I get the context so I can use public Intent (Context packageContext, Class<?> cls)?

  • Bardya Momeni
    Bardya Momeni over 7 years
    what you said is not true. you can start a service from BroadcastReceivers, but cannot bind to them.
  • Blasanka
    Blasanka over 5 years
    Oh seriously, I didnt see it until I see this.
  • Donald Duck
    Donald Duck over 2 years
    This doesn't work. I'm trying to call the broadcast from a service and the context I'm trying to get is a MyService object, but the context argument is a ReceiverRestrictedContext object.