Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 375
madu Avatar asked Nov 07 '10 04:11

madu


People also ask

What is context in broadcast receiver?

In Broadcast receiver, context refers to the activity or class in which the broadcast receiver is running.

What is the role of the onReceive () method in the BroadcastReceiver?

Retrieve the current result extra data, as set by the previous receiver. This can be called by an application in onReceive(Context, Intent) to allow it to keep the broadcast active after returning from that function.

Does the broadcast receiver onReceive () runs on main thread or background thread?

onReceive always run in the UI thread? Yes.

How pass data from BroadcastReceiver to activity in Android?

Intent intent = getIntent(); String message = intent. getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme.


2 Answers

public abstract void onReceive(Context context, Intent intent) 

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

like image 119
Falmarri Avatar answered Sep 20 '22 02:09

Falmarri


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

like image 22
Bibhay Ranjan Avatar answered Sep 18 '22 02:09

Bibhay Ranjan