解决android10(API 29)中NetworkInfo被废弃的问题

在API 29中,NetworkInfo被标记为弃用
在以往情况下,我们常用 NetworkInfo 来判断网络连接与否以及判断网络的类型,那么在Android 10中我们可以用 NetworkCapabilities 来代替

public class netWorkChangeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
       ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network network = connectivityManager.getActiveNetwork();
        if(network == null){
            Toast.makeText(context,"unavailable",Toast.LENGTH_LONG).show();
        }
        else{
            NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
            assert networkCapabilities != null;
            if(networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)){
                Toast.makeText(context,"Cellular",Toast.LENGTH_LONG).show();
            }
            if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)){
                Toast.makeText(context,"WIFI",Toast.LENGTH_LONG).show();
            }
        }

    }
}

由于getActiveNetwork需要api > 23,所以在使用时最好加入对于api版本的判断,在 23 以下的仍使用 NetworkInfo

上一篇:AlertDilog


下一篇:【Android】触发按钮的三种方式