溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android網(wǎng)絡(luò)監(jiān)聽和網(wǎng)絡(luò)判斷的示例分析

發(fā)布時間:2021-12-09 13:19:30 來源:億速云 閱讀:127 作者:柒染 欄目:開發(fā)技術(shù)

本篇文章給大家分享的是有關(guān)Android網(wǎng)絡(luò)監(jiān)聽和網(wǎng)絡(luò)判斷的示例分析,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

一、在AndroidMainfest.xml中添加權(quán)限

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

二、NetUtilSS 網(wǎng)絡(luò)判斷工具類

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;
    // 手機(jī)網(wǎng)絡(luò)數(shù)據(jù)連接
    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");
    }
 
    /**
     * 判斷網(wǎng)絡(luò)是否連接
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
 
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        // 如果僅僅是用來判斷網(wǎng)絡(luò)連接
 
        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網(wǎng)絡(luò)
     * @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網(wǎng)絡(luò),用戶的體現(xiàn)性在這里了,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;
    }
 
    /**
     * 打開網(wǎng)絡(luò)設(shè)置界面
     */
    public static void openSetting(final Activity activity) {
        Log.e("netutils", "我是網(wǎng)絡(luò)1111");
        final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("開啟網(wǎng)絡(luò)服務(wù)");
        builder.setMessage("網(wǎng)絡(luò)沒有連接,請到設(shè)置進(jìn)行網(wǎng)絡(luò)設(shè)置!");
        builder.setPositiveButton("確定",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            // 3.0以上打開設(shè)置界面,也可以直接用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", "我是網(wǎng)絡(luò)");
                    }
                });
        builder.show();
    }
 
    /**
     * 返回當(dāng)前網(wǎng)絡(luò)連接類型
     *
     * @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;
 
                }
 
        }
        // 網(wǎng)絡(luò)
        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: // 聯(lián)通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://有機(jī)型返回16,17
 
                            //中國移動 聯(lián)通 電信 三種3G制式
 
                            if (strSubTypeName.equalsIgnoreCase("TD-SCDMA") || strSubTypeName.equalsIgnoreCase("WCDMA") || strSubTypeName.equalsIgnoreCase("CDMA2000")) {
 
                                return NETWORN_3G;
 
                            } else {
 
                                return NETWORN_MOBILE;
 
                            }
                    }
                }
        }
        return NETWORN_NONE;
    }
}

三、IntentReceiver網(wǎng)絡(luò)監(jiān)聽工具類

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("網(wǎng)絡(luò)連接成功",1000);
                SpUtils.putString(context,"network","有網(wǎng)");
                isnet = false;
            }else{
                ToastUtils.getInstance(context).show("網(wǎng)絡(luò)開小差了",1000);
                SpUtils.putString(context,"network","無網(wǎng)");
                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已經(jīng)連接", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","有網(wǎng)");
            } else if (rd) {
                Toast.makeText(this, "手機(jī)流量已經(jīng)連接", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","有網(wǎng)");
            } else {
                Toast.makeText(this, "網(wǎng)絡(luò)連接不可用,請檢查網(wǎng)絡(luò)設(shè)置", Toast.LENGTH_SHORT).show();
                SpUtils.putString(this,"network","無網(wǎng)");
//                NetUtilSS.openSetting((Activity) mContext);
            }
        } else {
            Toast.makeText(this, "網(wǎng)絡(luò)連接不可用,請檢查網(wǎng)絡(luò)設(shè)置", Toast.LENGTH_SHORT).show();
            SpUtils.putString(this,"network","無網(wǎng)");
//            NetUtilSS.openSetting((Activity) mContext);
        }
    }
 
    public static boolean isNetwork(Context context){
        String network = SpUtils.getString(context, "network");
        if (network.equals("有網(wǎng)")){
            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,"有網(wǎng)");
            //請求
            //....
 
        }else {
            Log.e(TAG,"無網(wǎng)");
            //提示
            //....
        }
    }
}

以上就是Android網(wǎng)絡(luò)監(jiān)聽和網(wǎng)絡(luò)判斷的示例分析,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI