Android网络监听和网络判断的示例分析

发布时间:2021-12-09 13:19:30 作者:柒染
来源:亿速云 阅读:127

本篇文章给大家分享的是有关Android网络监听和网络判断的示例分析,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

一、在AndroidMainfest.xml中添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

二、NetUtilSS 网络判断工具类

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import java.util.List;
 
 
public class NetUtilSS {
    // 没有连接
    public static final int NETWORN_NONE = 0;
    // wifi连接
    public static final int NETWORN_WIFI = 1;
    // 手机网络数据连接
    public static final int NETWORN_2G = 2;
 
    public static final int NETWORN_3G = 3;
 
    public static final int NETWORN_4G = 4;
 
    public static final int NETWORN_MOBILE = 5;
 
    private NetUtilSS() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }
 
    /**
     * 判断网络是否连接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
 
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // 如果仅仅是用来判断网络连接
 
        if (null != connectivity) {
 
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }
 
    /**
     * 判断GPS是否打开
     *
     * @param context
     * @return
     */
 
    public static boolean isGpsEnabled(Context context) {
        LocationManager lm = ((LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE));
        List<String> accessibleProviders = lm.getProviders(true);
        return accessibleProviders != null && accessibleProviders.size() > 0;
    }
 
    /**
     * 判断是否是3G网络
     * @param context
     * @return
     */
 
    public static boolean is3rd(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null
                && networkINfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            return true;
        }
        return false;
    }
 
    /**
     * 判断是wifi还是3g网络,用户的体现性在这里了,wifi就可以建议下载或者在线播放。
     *
     * @param context
     * @return
     */
 
    public static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkINfo = cm.getActiveNetworkInfo();
        if (networkINfo != null
                && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }
 
    /**
     * 打开网络设置界面
     */
    public static void openSetting(final Activity activity) {
        Log.e("netutils", "我是网络1111");
        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("开启网络服务");
        builder.setMessage("网络没有连接,请到设置进行网络设置!");
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            // 3.0以上打开设置界面,也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
                            activity.startActivity(new Intent(
                                    android.provider.Settings.ACTION_SETTINGS));
                        } else {
                            activity.startActivity(new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                        }
                        dialog.cancel();
                    }
                });
 
        builder.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
 
                        Log.e("netutils", "我是网络");
                    }
                });
        builder.show();
    }
 
    /**
     * 返回当前网络连接类型
     *
     * @param context 上下文
     * @return
     */
    public static int getNetworkState(Context context) {
 
        ConnectivityManager connManager = (ConnectivityManager) context
 
                .getSystemService(Context.CONNECTIVITY_SERVICE);
 
        if (null == connManager)
 
            return NETWORN_NONE;
 
        NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
 
        if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
 
            return NETWORN_NONE;
 
        }
        // Wifi
        NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
 
        if (null != wifiInfo) {
 
            NetworkInfo.State state = wifiInfo.getState();
 
            if (null != state)
 
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
 
                    return NETWORN_WIFI;
 
                }
 
        }
        // 网络
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
 
        if (null != networkInfo) {
 
            NetworkInfo.State state = networkInfo.getState();
 
            String strSubTypeName = networkInfo.getSubtypeName();
 
            if (null != state)
                if (state == NetworkInfo.State.CONNECTED || state == NetworkInfo.State.CONNECTING) {
 
                    switch (activeNetInfo.getSubtype()) {
 
                        case TelephonyManager.NETWORK_TYPE_GPRS: // 联通2g
 
                        case TelephonyManager.NETWORK_TYPE_CDMA: // 电信2g
 
                        case TelephonyManager.NETWORK_TYPE_EDGE: // 移动2g
 
                        case TelephonyManager.NETWORK_TYPE_1xRTT:
 
                        case TelephonyManager.NETWORK_TYPE_IDEN:
 
                            return NETWORN_2G;
 
                        case TelephonyManager.NETWORK_TYPE_EVDO_A: // 电信3g
 
                        case TelephonyManager.NETWORK_TYPE_UMTS:
 
                        case TelephonyManager.NETWORK_TYPE_EVDO_0:
 
                        case TelephonyManager.NETWORK_TYPE_HSDPA:
 
                        case TelephonyManager.NETWORK_TYPE_HSUPA:
 
                        case TelephonyManager.NETWORK_TYPE_HSPA:
 
                        case TelephonyManager.NETWORK_TYPE_EVDO_B:
 
                        case TelephonyManager.NETWORK_TYPE_EHRPD:
 
                        case TelephonyManager.NETWORK_TYPE_HSPAP:
 
                            return NETWORN_3G;
 
                        case TelephonyManager.NETWORK_TYPE_LTE:
 
                            return NETWORN_4G;
 
                        default://有机型返回16,17
 
                            //中国移动 联通 电信 三种3G制式
 
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
 
                                return NETWORN_3G;
 
                            } else {
 
                                return NETWORN_MOBILE;
 
                            }
                    }
                }
        }
        return NETWORN_NONE;
    }
}

三、IntentReceiver网络监听工具类

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
 
public class IntentReceiver extends BroadcastReceiver {
    private boolean isnet ;
    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = manager.getActiveNetworkInfo();
        if (isnet == true){
            if (activeNetworkInfo != null && activeNetworkInfo.isAvailable()){
                ToastUtils.getInstance(context).show("网络连接成功",1000);
                SpUtils.putString(context,"network","有网");
                isnet = false;
            }else{
                ToastUtils.getInstance(context).show("网络开小差了",1000);
                SpUtils.putString(context,"network","无网");
                isnet = true;
            }
        }else{
            isnet = true;
        }
        isnet = true;
    }
}

四、BaseActivity

import androidx.appcompat.app.AppCompatActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.widget.Toast;
 
public class BaseActivity extends AppCompatActivity {
 
    private BroadcastReceiver receiver =  new IntentReceiver();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
 
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver,filter);
 
        boolean connected = NetUtilSS.isConnected(this);
        if (connected) {
            boolean wifi = NetUtilSS.isWifi(this);
            boolean rd = NetUtilSS.is3rd(this);
            if (wifi) {
                Toast.makeText(this, "WIFI已经连接", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","有网");
            } else if (rd) {
                Toast.makeText(this, "手机流量已经连接", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","有网");
            } else {
                Toast.makeText(this, "网络连接不可用,请检查网络设置", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","无网");
//                NetUtilSS.openSetting((Activity) mContext);
            }
        } else {
            Toast.makeText(this, "网络连接不可用,请检查网络设置", Toast.LENGTH_SHORT).show();
            SpUtils.putString(this,"network","无网");
//            NetUtilSS.openSetting((Activity) mContext);
        }
    }
 
    public static boolean isNetwork(Context context){
        String network = SpUtils.getString(context, "network");
        if (network.equals("有网")){
            return true;
        }
        return false;
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
 
}

五、MainActivity   

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
 
public class MainActivity extends BaseActivity {
 
    String TAG  =  "MainActivity";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
 
        if (isNetwork(this)){
            Log.e(TAG,"有网");
            //请求
            //....
 
        }else {
            Log.e(TAG,"无网");
            //提示
            //....
        }
    }
}

以上就是Android网络监听和网络判断的示例分析,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. Android Junit Test的示例分析
  2. Android Gradle开发的示例分析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

android

上一篇:Apache下分析ab性能测试的结果是什么

下一篇:怎样解析TypeScript基础类型

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》