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

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

问题描述

我想在广播接收器中检查互联网连接;并将结果(布尔标志)设置为全局变量,以在整个应用程序中使用它,在 if 条件下;如果互联网断开连接,请将主活动中的状态图像视图设置为红色图像,如果已连接,则将其设置为绿色.

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.

我关注了这个主题.但是广播接收器中没有getApplication();我应该使用 getApplicationContext() 代替.

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

另一方面,这个主题:

在广播接收器中编写代码时,它不是上下文而是在它的 onReceive 方法中给出了一个上下文,你只能调用获取应用程序上下文().这也意味着您无法得到保证在 BroadcastReceiver 中访问您的应用程序.

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. 有哪些顾虑?

  1. What are the concerns?

如何在广播接收器中访问我的应用程序类?

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

是否有更好的解决方案来检查互联网连接、设置全局变量和更改我的状态图像视图?

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

推荐答案

您可以使用 BroadCastReceiver 的上下文访问您的 Application 类,

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天全站免登陆