[英]android Connectivity_Change broadcastreceiver not getting called consistently
I am trying to test/implement lost network use case. 我正在尝试测试/实现丢失的网络用例。 I have code as mentioned below. 我有下面提到的代码。
I run it on Galaxy S6. 我在Galaxy S6上运行它。 I have both mobile data and wifi enabled. 我同时启用了移动数据和wifi。
To disable network, I turn on "Airplane Mode" 要禁用网络,请打开“飞行模式”
My issue is: 我的问题是:
If I relaunch app from android studio, I do get ConnectionChangeReceiver.onReceive()
called. 如果我从android studio重新启动应用程序,则会调用ConnectionChangeReceiver.onReceive()
。 However, after few turn on/off Airplane mode, I do not get onReceive()
called. 但是,在几次打开/关闭飞行模式后,我没有调用onReceive()
。
I set breakpoint in studio to check if its called or not. 我在Studio中设置了断点,以检查是否调用了断点。
Am I missing something? 我想念什么吗?
public class ConnectionChangeReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
// get Connectivity Manager object to check connection
ConnectivityManager connectivityManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
// Check for network connections
if ( activeNetInfo != null && activeNetInfo.isConnected()) {
Intent newintent = new Intent(BroadcastedIntentFilters.INTERNET_CONNECTED);
LocalBroadcastManager.getInstance(context).sendBroadcast(newintent);
}
}
}
In manifest file 在清单文件中
<receiver
android:name=".Network.ConnectionChangeReceiver"
android:exported="true"
android:label="NetworkConnection" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
In Android 5.0 and higher you have to monitor changes by connectivityManager.registerNetworkCallback
which is different in comparison to earlier versions where you should listen in BroadcastReveiver
. 在Android 5.0及更高版本中,您必须通过connectivityManager.registerNetworkCallback
监视更改,该更改与应在BroadcastReveiver
监听的早期版本相比有所不同。
I wrote a simple class which supports all Android versions and allows monitoring changes and ask about current state as well. 我编写了一个简单的类,该类支持所有Android版本,并允许监视更改并询问当前状态。
https://github.com/mklimek/network-availability https://github.com/mklimek/network-availability
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.