欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android网络监听和网络判断示例介绍

时间:2023-01-17 12:46:56|栏目: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,"无网");
            //提示
            //....
        }
    }
}

上一篇:ExpandableListView实现二级列表购物车

栏    目:Android代码

下一篇:Flutter集成高德地图并添加自定义Maker的实践

本文标题:Android网络监听和网络判断示例介绍

本文地址:http://www.codeinn.net/misctech/223855.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有