Android-从 Broadcast 接收器 onRecept()获取要发送到的上下文

我基本上想要创建一个意图,并将其传递给来自 BroadcastReceiver 的 onReceive ()的服务。

到目前为止,我一直使用 View.getContext () ,但是在这里,我卡住了。 我到底如何才能得到上下文,以便我可以使用 public Intent (Context packageContext, Class<?> cls)

46219 次浏览
public abstract void onReceive(Context context, Intent intent)

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

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

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