android10中NetworkInfo废弃如何解决

怕内容失效,留存

在API 29中,NetworkInfo被标记为弃用。在以往情况下,我们常用 NetworkInfo 来判断网络连接与否以及判断网络的类型,那么在Android 10中我们可以用 NetworkCapabilities 来代替。代码中,由于getActiveNetwork需要API > 23,所以在使用时最好加入对于API版本的判断,在 23 以下的仍使用 NetworkInfo。

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();
            }
        }

    }
}

————————————————
版权声明:本文为CSDN博主「Temple_of_light」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/Mr_nuts/article/details/115031075

更详细说明:https://blog.csdn.net/SweetTool/article/details/105377697

————————————————
版权声明:本文为CSDN博主「二流小宝」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/SweetTool/article/details/105377697

原文地址:https://www.cnblogs.com/hi-yxiao/p/14832286.html