其他分享
首页 > 其他分享> > 解决android10(API 29)中NetworkInfo被废弃的问题

解决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

标签:Toast,networkCapabilities,show,NetworkInfo,android10,29,context,NetworkCapabilit
来源: https://blog.csdn.net/Mr_nuts/article/details/115031075