Commit 420ee7a0 by pye52

整理网络工具类

parent 15046def
......@@ -29,11 +29,9 @@ import com.bgycc.smartcanteen.state.ConnectState;
import com.bgycc.smartcanteen.state.PayOfflineState;
import com.bgycc.smartcanteen.state.PayOnlineState;
import com.bgycc.smartcanteen.state.QRCodeState;
import com.bgycc.smartcanteen.utils.EthernetHelper;
import com.bgycc.smartcanteen.utils.NetworkHelper;
import com.bgycc.smartcanteen.utils.NetworkUtils;
import com.bgycc.smartcanteen.utils.SmartCanteenUtils;
import com.bgycc.smartcanteen.utils.TTSHelper;
import com.bgycc.smartcanteen.utils.WifiHelper;
import com.bgycc.smartcanteen.viewModel.CommandViewModel;
import com.bgycc.smartcanteen.viewModel.PayOfflineViewModel;
import com.bgycc.smartcanteen.viewModel.PayOnlineViewModel;
......@@ -84,8 +82,8 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
super.attachBaseContext(newBase);
deviceSN = SmartCanteenUtils.getDeviceSN(newBase.getApplicationContext());
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
NetworkHelper.initialize(newBase.getApplicationContext());
TTSHelper.initialize(newBase.getApplicationContext());
NetworkUtils.initialize(newBase.getApplicationContext());
if (deviceSN.isEmpty()) {
LogUtils.file(TAG, "设备SN号为空");
......@@ -119,7 +117,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
SCWebSocketClient.getInstance().getConnectStateEvent().observe(this, event -> {
if (debugVs != null) return;
String networkType = NetworkHelper.getNetworkType(this);
String networkType = NetworkUtils.getNetworkType(this);
String msg;
switch (event.getState()) {
case ConnectState.OFFLINE:
......@@ -240,6 +238,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
break;
case CommandState.WAIT:
settingLayout.animate().setDuration(300).alpha(1f);
settingText.setText(event.getMessage());
break;
case CommandState.SUCCESS:
case CommandState.FAILED:
......@@ -316,7 +315,7 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
protected void onDestroy() {
super.onDestroy();
TTSHelper.release();
SCWebSocketClient.getInstance().close();
SCWebSocketClient.getInstance().realClose();
SCTaskExecutor.getInstance().quit();
}
......@@ -365,15 +364,15 @@ public class MainActivity extends AppCompatActivity implements View.OnClickListe
}
private void refreshEthInfo() {
String ethMac = EthernetHelper.getMacAddress();
String ethIP = EthernetHelper.getIpString();
String ethMac = NetworkUtils.getEthernetMacAddress();
String ethIP = NetworkUtils.getEthernetIpString();
ethText.setText(String.format(Locale.getDefault(), getString(R.string.eth_text), ethMac, ethIP));
}
private void refreshWifiInfo() {
String wifiMac = WifiHelper.getMacAddress();
String wifiSSID = WifiHelper.getSSID();
String wifiIP = WifiHelper.getIpString();
String wifiMac = NetworkUtils.getWifiMacAddress();
String wifiSSID = NetworkUtils.getSSID();
String wifiIP = NetworkUtils.getWifiIpString();
wifiText.setText(String.format(Locale.getDefault(), getString(R.string.wifi_text), wifiMac, wifiSSID, wifiIP));
}
......
package com.bgycc.smartcanteen.utils;
import com.blankj.utilcode.util.LogUtils;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import static com.bgycc.smartcanteen.utils.SmartCanteenUtils.TAG;
public class EthernetHelper {
public static String getMacAddress() {
try {
NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
if (networkInterface == null) {
return "";
}
byte[] data = networkInterface.getHardwareAddress();
return String.format("%02x:%02x:%02x:%02x:%02x:%02x", data[0], data[1], data[2], data[3], data[4], data[5]);
} catch (Exception e) {
LogUtils.e(TAG, "获取设备MAC地址失败: " + e.getMessage(), e);
}
return "02:00:00:00:00:00";
}
public static String getIpString() {
try {
NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
if (networkInterface == null) {
return "";
}
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String address = inetAddress.getHostAddress();
if(!address.contains("::")) return address;
}
}
} catch (Exception e) {
LogUtils.e(TAG, "获取以太网ip地址失败: " + e.getMessage(), e);
}
return "0.0.0.0";
}
}
package com.bgycc.smartcanteen.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Build;
import androidx.annotation.NonNull;
import com.bgycc.smartcanteen.R;
import com.blankj.utilcode.util.LogUtils;
import static com.bgycc.smartcanteen.utils.SmartCanteenUtils.TAG;
public class NetworkHelper {
private static ConnectivityManager connectivityManager;
private static int transportType = NetworkCapabilities.TRANSPORT_WIFI;
public static void initialize(Context context) {
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
}
public static String getNetworkType(Context context) {
switch (transportType) {
case NetworkCapabilities.TRANSPORT_ETHERNET:
return context.getString(R.string.network_type_ethernet);
case NetworkCapabilities.TRANSPORT_WIFI:
return context.getString(R.string.network_type_wifi);
default:
return context.getString(R.string.network_type_unknown);
}
}
public static synchronized void switchNetwork() {
if (transportType == NetworkCapabilities.TRANSPORT_ETHERNET) {
requestWifi();
} else {
requestEthernet();
}
}
private static void requestEthernet() {
if (connectivityManager == null) {
LogUtils.w(TAG, "ConnectivityManager should be initialize before use");
return;
}
int targetTransportType = NetworkCapabilities.TRANSPORT_ETHERNET;
if (!hasTransport(targetTransportType)) {
LogUtils.d(TAG, "当前设备不支持通过以太网链接网络");
return;
}
transportType = targetTransportType;
LogUtils.d(TAG, "网络切换至以太网");
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(transportType)
.build();
connectivityManager.requestNetwork(request, createCallback());
}
private static void requestWifi() {
if (connectivityManager == null) {
LogUtils.w(TAG, "ConnectivityManager should be initialize before use");
return;
}
int targetTransportType = NetworkCapabilities.TRANSPORT_WIFI;
if (!hasTransport(targetTransportType)) {
LogUtils.d(TAG, "当前设备不支持通过Wifi链接网络");
return;
}
transportType = targetTransportType;
LogUtils.d(TAG, "网络切换至Wifi");
NetworkRequest request = new NetworkRequest.Builder()
.addTransportType(transportType)
.build();
connectivityManager.requestNetwork(request, createCallback());
}
private static boolean hasTransport(int transportType) {
Network[] networks = connectivityManager.getAllNetworks();
NetworkCapabilities capabilities;
for (Network n : networks) {
capabilities = connectivityManager.getNetworkCapabilities(n);
if (capabilities == null) continue;
if (capabilities.hasTransport(transportType)) {
return true;
}
}
return false;
}
private static ConnectivityManager.NetworkCallback createCallback() {
return new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
LogUtils.i(TAG, "网络切换成功: " + network);
if (Build.VERSION.SDK_INT >= 23) {
connectivityManager.bindProcessToNetwork(network);
} else {
ConnectivityManager.setProcessDefaultNetwork(network);
}
connectivityManager.unregisterNetworkCallback(this);
}
@Override
public void onUnavailable() {
super.onUnavailable();
LogUtils.i(TAG, "网络切换失败: " + transportType);
}
};
}
}
package com.bgycc.smartcanteen.utils;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.Utils;
import java.net.NetworkInterface;
import java.util.List;
import static com.bgycc.smartcanteen.utils.SmartCanteenUtils.TAG;
@SuppressWarnings("all")
public class WifiHelper {
private static WifiManager getWifiManager() {
return (WifiManager) Utils.getApp().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
}
public static DhcpInfo getDhcpInfo() {
try {
return getWifiManager().getDhcpInfo();
} catch (Exception e) {
LogUtils.w(TAG, "获取Dhcp信息异常: " + e.getMessage(), e);
}
return null;
}
public static WifiInfo getWifiInfo() {
try {
return getWifiManager().getConnectionInfo();
} catch (Exception e) {
LogUtils.w(TAG, "获取Wifi信息异常: " + e.getMessage(), e);
}
return null;
}
public static String getMacAddress() {
try {
NetworkInterface networkInterface = NetworkInterface.getByName("wlan0");
byte[] data = networkInterface.getHardwareAddress();
return String.format("%02x:%02x:%02x:%02x:%02x:%02x", data[0], data[1], data[2], data[3], data[4], data[5]);
} catch (Exception e) {
LogUtils.w(TAG, "获取MAC地址异常: " + e.getMessage(), e);
}
return "02:00:00:00:00:00";
}
public static int getWifiNetworkID() {
WifiInfo wifiInfo = getWifiInfo();
if (wifiInfo == null) {
return 0;
}
try {
return wifiInfo.getNetworkId();
} catch (Exception e) {
LogUtils.w(TAG, "获取Wifi Id异常: " + e.getMessage(), e);
}
return 0;
}
public static boolean setEnable(boolean enable) {
try {
if (isWifiEnabled()) return true;
return getWifiManager().setWifiEnabled(enable);
} catch (Exception e) {
LogUtils.w(TAG, "Wifi启动异常: " + e.getMessage(), e);
return false;
}
}
public static boolean isWifiEnabled() {
try {
return getWifiManager().isWifiEnabled();
} catch (Exception e) {
LogUtils.w(TAG, "Wifi状态检查异常: " + e.getMessage(), e);
}
return false;
}
public static String getSSID() {
WifiInfo wifiInfo = getWifiInfo();
if (wifiInfo == null) {
return "02:00:00:00:00:00";
}
try {
return wifiInfo.getSSID();
} catch (Exception e) {
LogUtils.w(TAG, "获取Wifi SSID异常: " + e.getMessage(), e);
return "02:00:00:00:00:00";
}
}
public static String getIpString() {
WifiInfo wifiInfo = getWifiInfo();
if (wifiInfo == null) {
return "0.0.0.0";
}
try {
int ip = wifiInfo.getIpAddress();
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
((ip >> 24) & 0xFF);
} catch (Exception e) {
LogUtils.w(TAG, "获取Wifi IP地址异常: " + e.getMessage(), e);
return "0.0.0.0";
}
}
public static WifiConfiguration getWifiConfiguration(String ssid) {
try {
List<WifiConfiguration> existingConfigs = getWifiManager().getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals("\"" + ssid + "\"")) {
return existingConfig;
}
}
} catch(Exception e) {
LogUtils.w(TAG, "获取Wifi配置异常: " + e.getMessage(), e);
}
return null;
}
public static boolean removeWifiConfiguration(String ssid) {
try {
WifiConfiguration wifiConfig = getWifiConfiguration(ssid);
if(wifiConfig != null) {
return getWifiManager().removeNetwork(wifiConfig.networkId);
}
} catch (Exception e) {
LogUtils.w(TAG, "移除Wifi配置异常: " + e.getMessage(), e);
}
return false;
}
protected static WifiConfiguration createWifiConfiguration(String ssid, String pwd, String type) {
return createWifiConfiguration(ssid, null, pwd, type);
}
public static WifiConfiguration createWifiConfiguration(String ssid, String identity, String pwd, String type) {
if(ssid == null || ssid.isEmpty())
return null;
if (pwd != null && !pwd.isEmpty()) {
if (type == null || type.isEmpty())
type = "wpa";
}
else {
type = null;
}
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
config.SSID = "\"" + ssid + "\"";
if (type == null) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
} else if ("wep".compareToIgnoreCase(type) == 0) {
config.hiddenSSID = true;
config.wepKeys[0] = "\"" + pwd + "\"";
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
} else if ("wpa".compareToIgnoreCase(type) == 0) {
config.preSharedKey = "\"" + pwd + "\"";
config.hiddenSSID = true;
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
config.status = WifiConfiguration.Status.ENABLED;
} else if ("wpa_eap".compareToIgnoreCase(type) == 0) {
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
WifiEnterpriseConfig enterpriseConfig = new WifiEnterpriseConfig();
enterpriseConfig.setIdentity(identity);
enterpriseConfig.setPassword(pwd);
enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
config.enterpriseConfig = enterpriseConfig;
} else {
return null;
}
return config;
}
public static int addNetwork(WifiConfiguration config) {
return getWifiManager().addNetwork(config);
}
public static boolean enableNetwork(int netId) {
return getWifiManager().enableNetwork(netId, true);
}
public static boolean connect(String ssid, String identity, String pwd, String type) {
WifiConfiguration config = createWifiConfiguration(ssid, identity, pwd, type);
if (config == null) {
return false;
}
if (!isWifiEnabled()) {
return false;
}
WifiManager wifiManager = getWifiManager();
boolean ret = removeWifiConfiguration(ssid);
int netId = wifiManager.addNetwork(config);
if (!wifiManager.enableNetwork(netId, true)) {
return false;
}
wifiManager.reconnect();
return true;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment