wifi 状态下,只能获取到路由分配的内部地址192.168.xxx.xxx 无法获取真实服务器地址,(可以依赖对外部网络请求返回,来获取自己的真实服务器地址)
import android.app.Application;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.RemoteException;
import com.kalerm.android.pbjx.app.iot.bean.NetworkType;
import com.kalerm.android.pbjx.app.ui.online.bean.CommonBean;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.Locale;
/**
* 2023/11/6
* ..╭︿︿︿╮
* {/ . . /}
* .( (oo) ) create by cps
* .︶︶︶
* for 计算网络数据统计
*/
public class NetworkByteUtil {
private Context context;
private static NetworkByteUtil mInstance;
private NetworkByteUtil(Application application) {
context = application;
}
public static NetworkByteUtil getInstance(Application application) {
if (mInstance == null) {
mInstance = new NetworkByteUtil(application);
}
return mInstance;
}
/**
* @param DataType 数据类型 0:移动网络 1:wifi 其他:全部数据
* @param dateType 日期类型 0:本日 1:本月
* @return 接受与发送的总和
*/
public long getDataByteByType(int DataType, int dateType) {
NetworkStatsManager networkStatsManager = (NetworkStatsManager)
context.getSystemService(Context.NETWORK_STATS_SERVICE);
long endTime = System.currentTimeMillis();
long startLongTime;
if (dateType == 0) {
startLongTime = getTodayLongTime();
} else {
startLongTime = getCMonthLongTime();
}
if (startLongTime < 1) {
return -1;
}
CommonBean result = new CommonBean();
try {
switch (DataType) {
case 0:
NetworkStats.Bucket bucketOnlyMobile = networkStatsManager
.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null,
startLongTime, endTime);//整机
// networkStatsManager.querySummary();//当前应用
result.setData1(bucketOnlyMobile.getRxBytes());
result.setData2(bucketOnlyMobile.getTxBytes());
break;
case 1:
NetworkStats.Bucket bucketOnlyWifi = networkStatsManager
.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null,
startLongTime, endTime);
result.setData1(bucketOnlyWifi.getRxBytes());
result.setData2(bucketOnlyWifi.getTxBytes());
break;
default:
NetworkStats.Bucket bucketMobile = networkStatsManager
.querySummaryForDevice(ConnectivityManager.TYPE_MOBILE, null,
startLongTime, endTime);
NetworkStats.Bucket bucketWifi = networkStatsManager
.querySummaryForDevice(ConnectivityManager.TYPE_WIFI, null,
startLongTime, endTime);
long rxBytes = bucketMobile.getRxBytes() + bucketWifi.getRxBytes();
long txBytes = bucketMobile.getTxBytes() + bucketWifi.getTxBytes();
result.setData1(rxBytes);
result.setData2(txBytes);
break;
}
} catch (RemoteException e) {
e.printStackTrace();
return -1;
}
LogUtil.d("query bytes is received:" + result.getData1() + ".Sent :" + result.getData2());
return result.getData1() + result.getData2();
}
private long getTodayLongTime() {
String dateStr = TimeUtil.getDate();//"yyyy/MM/dd"
long longTimeByTag = TimeUtil.getLongTimeByTag(dateStr, "yyyy/MM/dd");
LogUtil.d("start query net—data day-time is :" + longTimeByTag);
return longTimeByTag;
}
private long getCMonthLongTime() {
String dateStr = TimeUtil.formatDateByTimeL(System.currentTimeMillis(), "yyyy/MM") + "/01";//"yyyy/MM/dd"
long longTimeByTag = TimeUtil.getLongTimeByTag(dateStr, "yyyy/MM/dd");
LogUtil.d("start query net—data month-time is :" + longTimeByTag);
return longTimeByTag;
}
public String getLocalIpAddress() {
String resultIp = "";
String netWorkType = AndroidUtil.getNetWorkType(context);
if (netWorkType.equals("WIFI")) {
try {
resultIp = getWifiIpAddress();
} catch (Exception e) {
e.printStackTrace();
}
} else if (netWorkType.equals("MOBILE")) {
try {
resultIp = getMobileIpAddress();
} catch (SocketException e) {
e.printStackTrace();
}
}
return resultIp;
}
private String getWifiIpAddress() throws Exception {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String beDispatchedIpStr = String.format(Locale.getDefault(), "%d.%d.%d.%d", (ipAddress & 0xff)
, (ipAddress >> 8 & 0xff)
, (ipAddress >> 16 & 0xff)
, (ipAddress >> 24 & 0xff));
LogUtil.d("wifi dispatched Ip IS :" + beDispatchedIpStr);
return beDispatchedIpStr;
}
/**
* found ip is:fe80::6065:1ff:fe95:3626%dummy0
* found ip is:::1
* found ip is:127.0.0.1
* found ip is:fe80::d87e:bde3:e5b3:a734%rmnet_data0
* found ip is:fe80::4fe0:305f:9deb:3f77%rmnet_data2
* found ip is:2409:8920:4c51:44e0:4fe0:305f:9deb:3f77
* found ip is:10.62.147.249
* found ip is:fe80::9287:ab5:1161:7ec4%rmnet_data1
* found ip is:2409:8121:4d70:9e2a:9287:ab5:1161:7ec4
* <p>
* <p>
*/
private String getMobileIpAddress() throws SocketException {
String ipv4String = "";
String ipv6String = "";
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (!networkInterface.isUp()) {
continue;
}
Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
while (inetAddresses.hasMoreElements()) {
InetAddress inetAddress = inetAddresses.nextElement();
// if (!inetAddress.isLoopbackAddress()&&inetAddress.isSiteLocalAddress()){
// 此方式也可获得IPV4 ip值
// }
LogUtil.d("found ip is: " + inetAddress.toString());
if (inetAddress instanceof Inet4Address) {
ipv4String = inetAddress.getHostAddress();
} else if (inetAddress instanceof Inet6Address) {
ipv6String = inetAddress.getHostAddress();
}
}
}
LogUtil.d("ipv4: " + ipv4String + " ipv6 : " + ipv6String);
return ipv4String;
}
/**
* : mac address is : 04:86:80:4A:DF:EE
*
* @return
* @throws SocketException
*/
public String getMacAddress() throws SocketException {
String macAddressStr = "";
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getName().equalsIgnoreCase("wlan0")) {
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes != null && macBytes.length > 0) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : macBytes) {
stringBuilder.append(String.format("%02X:", b));
}
macAddressStr = stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
break;
}
}
}
LogUtil.d("mac address is : " + macAddressStr);
return macAddressStr;
}
}