Android判断是否有网络

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zqd1984309864/article/details/84347873
广播实现,起到提示用户作用
public void onReceive(Context context, Intent intent) {
    //通过getSystemService()方法得到connectionManager这个系统服务类,专门用于管理网络连接
    ConnectivityManager connectionManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isAvailable()) {
        Toast.makeText(context, "网络可用", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show();
    }
}

猜你喜欢

转载自blog.csdn.net/zqd1984309864/article/details/84347873