Ниже приведен код: всякий раз, когда я меняю свою сеть с Wi-Fi или сотовой связи, в автономном режиме или онлайн, метод OnReceive не вызывается.
В AndroidManifest.xml
<receiver
android:name=".offline.NetworkStatusReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
NetworkStatusReceiver.java
public class NetworkStatusReceiver extends BroadcastReceiver
{
private static final String TAG = BroadcastReceiver.class.getSimpleName();
@Override
public void onReceive( Context context, Intent intent )
{
if( intent.getAction().equals(
ConnectivityManager.CONNECTIVITY_ACTION ) )
{
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(((cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)!=null)&&
(cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)) ||
((cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)!=null)&&
(cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)))
{
// Perform some action with wifi connection
}
else
{
// Perform some action without wifi connection
}
}
}