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網絡監聽和網絡判斷示例介紹的文章就介紹到這瞭,更多相關Android網絡監聽和網絡判斷內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- android獲取及監聽手機網絡狀態
- Android自動攔截與接聽功能APK黑白名單
- 詳解Android的四大應用程序組件
- 詳解Android studio實現語音轉文字功能
- android實現動態顯示隱藏進度條