我想在 Broadcast Receiver 中检查互联网连接;并将结果( bool 标志)设置为全局变量,以便在 if 条件下将其用于整个应用程序;如果互联网断开连接,则在主要 Activity 中将状态 ImageView 设置为红色图像,如果已连接,则将其设置为绿色。
我关注了this话题。但是Broadcast Receiver中没有getApplication()
;我应该改用 getApplicationContext()
。
另一方面,this主题:
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.
有什么顾虑?
如何在广播接收器中访问我的应用程序类?
是否有更好的解决方案来检查互联网连接、设置全局变量和更改我的状态 ImageView ?
最佳答案
您可以使用其上下文访问 BroadCastReceiver
中的 Application
类,
@Override
public void onReceive(final Context context, Intent intent) {
MyApplication mApplication = ((MyApplication)context.getApplicationContext());
}
关于broadcastreceiver - 访问广播接收器中的应用程序类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24825684/