2.5 mac地址存储文件(mac获取失败就随机一个);监听返回按键,提示是否退出程序的提示窗口

This commit is contained in:
2025-04-18 09:57:07 +08:00
parent 2d43980458
commit c5579771d9
3 changed files with 60 additions and 6 deletions

View File

@ -22,6 +22,7 @@ import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Random;
import chaoran.business.BuildConfig;
@ -67,12 +68,29 @@ public class LocalAddressUtil {
@SuppressLint("JavascriptInterface")
@JavascriptInterface
public String getMacAddress(){//可以兼容安卓7以下
SharedPreferences spf = context.getSharedPreferences("chaoran_mac", Context.MODE_PRIVATE);
String saveMac = spf.getString("chaoran_mac", "");
if (!"".equalsIgnoreCase(saveMac)) {
return saveMac;
}
SharedPreferences.Editor editor = spf.edit();
String androidMac = getAndroidMac();
editor.putString("chaoran_mac", androidMac);
editor.apply();
return androidMac;
}
/**
* 获取安卓的mac
* @return
*/
private String getAndroidMac() {
if (Build.VERSION.SDK_INT >= 34) { // Android 14 is code-named Tiramisu
try {
return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
}catch (Exception e) {
e.printStackTrace();
return "02:00:00:00:00:02";
return generateRandomMacAddress();
}
}
String macAddress = null;
@ -84,7 +102,7 @@ public class LocalAddressUtil {
networkInterface = NetworkInterface.getByName("wlan0");
}
if (networkInterface == null) {
return "02:00:00:00:00:02";
return generateRandomMacAddress();
}
byte[] addr = networkInterface.getHardwareAddress();
for (byte b : addr) {
@ -94,12 +112,28 @@ public class LocalAddressUtil {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
} catch (SocketException e) {
} catch (Exception e) {
e.printStackTrace();
return "02:00:00:00:00:02";
macAddress = generateRandomMacAddress();
}
if (macAddress.length() < 4) {
macAddress = generateRandomMacAddress();
}
return macAddress;
}
private static String generateRandomMacAddress() {
Random rand = new Random();
byte[] macBytes = new byte[6];
rand.nextBytes(macBytes);
macBytes[0] = (byte) (macBytes[0] & 0xfe | 0x02);
StringBuilder macAddress = new StringBuilder();
for (int i = 0; i < macBytes.length; i++) {
macAddress.append(String.format("%02X%s", macBytes[i], (i < macBytes.length - 1) ? ":" : ""));
}
return macAddress.toString();
}
@SuppressLint("JavascriptInterface")
@JavascriptInterface
public String getInfo(int type){