访问应用程序类的广播接收器 [英] Access to application class in Broadcast Receiver

查看:291
本文介绍了访问应用程序类的广播接收器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查在广播接收机的网络连接;并设置结果(一个布尔标志),以一个全局变量,把它用在整个应用程序,如果在条件;如果网络断开,坐落在主要活动状态的ImageView,红色形象,如果连接,将其设置为绿色。

我跟着这个话题。但没有 getApplication()在广播接收器;和ii应该使用 getApplicationContext()代替。

在另一边,主题:


  

当在广播接收器,这不是一个上下文写入code,但
  给予其的onReceive方法的情况下,你只能叫
  getApplicationContext()。这也意味着,你不能保证
  不得不在广播接收器应用程序的访问。



  1. 什么顾虑?


  2. 我如何访问我的应用程序类广播接收机?


  3. 有没有更好的解决方案,检查互联网连接,设置全局变量和更改我的状态ImageView的?



解决方案

您可以访问你的应用广播接收器通过使用它的上下文中,

  @覆盖
 公共无效的onReceive(最终上下文的背景下,意图意图){
   所有MyApplication mApplication =((所有MyApplication)context.getApplicationContext());
 }

I want to check internet connection in Broadcast Receiver; And set result (A boolean flag) to a global variable, to use it on whole application, in if conditions; That if internet is disconnected, set a status imageview in main activity, to red image, and if connected, set it to green.

I followed this topic. But there is no getApplication() in Broadcast Receiver; And iI should use getApplicationContext() instead.

On another side, this topic:

when writing code in a broadcast receiver, which is not a context but is given a context in its onReceive method, you can only call getApplicationContext(). Which also means that you are not guaranteed to have access to your application in a BroadcastReceiver.

  1. What are the concerns?

  2. How can I access to my application class in broadcast Receiver?

  3. Is there better solution to check internet connection, set global variable and change my status imageview?

解决方案

You can access your Application class in BroadCastReceiver by using its context,

 @Override
 public void onReceive(final Context context, Intent intent) {
   MyApplication mApplication = ((MyApplication)context.getApplicationContext());
 }

这篇关于访问应用程序类的广播接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆