ConnectivityManager.Дополнительное отсутствие подключения всегда ложно на Android Lollipop

Я использую этот фрагмент кода для обнаружения изменений состояния подключения к интернету. Он отлично работает на Android

intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY)

всегда ложно. Как сделать этот код работать на Android 5.0?

My BroadcastReceiver:

public class NetworkStateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, final Intent intent) {
        if(intent.getExtras()!=null) {
            final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if(networkInfo != null && networkInfo.isConnectedOrConnecting()) {
                Log.d("receiver test", "detected on");
            }
        }
        Log.d("receiver test", Boolean.toString(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY)));
        if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
            Log.d("receiver test", "detected off");
        }
    }
}

1 ответов


можно использовать NetworkRequest добавлено в API уровня 21.

создайте пользовательское действие намерения:

public static final String CONNECTIVITY_ACTION_LOLLIPOP = "com.example.CONNECTIVITY_ACTION_LOLLIPOP";

создать новый метод registerConnectivityActionLollipop:

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void registerConnectivityActionLollipop() {

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        return;

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkRequest.Builder builder = new NetworkRequest.Builder();

    connectivityManager.registerNetworkCallback(builder.build(), new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            Intent intent = new Intent(CONNECTIVITY_ACTION_LOLLIPOP);
            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

            sendBroadcast(intent);
        }

        @Override
        public void onLost(Network network) {
            Intent intent = new Intent(CONNECTIVITY_ACTION_LOLLIPOP);
            intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);

            sendBroadcast(intent);
        }
    });
}

добавьте новое действие intent в фильтр intent и вызовите registerConnectivityActionLollipop:

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(CONNECTIVITY_ACTION_LOLLIPOP);

registerReceiver(mBroadcastReceiver, intentFilter);
registerConnectivityActionLollipop();

изменить BroadcastReceiver для поддержки нового действия намерения:

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP && TextUtils.equals(intent.getAction(), ConnectivityManager.CONNECTIVITY_ACTION) ||
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && TextUtils.equals(intent.getAction(), CONNECTIVITY_ACTION_LOLLIPOP)) {

            if (intent.getExtras() != null) {
                final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
                    Log.d("receiver test", "detected on");
                }
            }

            Log.d("receiver test", Boolean.toString(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY)));
            if (intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
                Log.d("receiver test", "detected off");
            }
        }
    }
};