浏览代码

Calculating upload & download speed of network via TrafficStats API on android on OpenVPN protocol & WireGuard

Khubaib 8 月之前
父节点
当前提交
b714cccaeb

+ 2 - 2
app/src/main/java/com/vpn/fastestvpnservice/screens/bottomNavBarScreens/HomeScreen.kt

@@ -115,8 +115,8 @@ var protocolObj: MutableState<Protocol> = mutableStateOf(
 var StringDown: MutableState<Double> = mutableStateOf(0.0)
 var StringUp: MutableState<Double> = mutableStateOf(0.0)
 
-var StringDownUnit: MutableState<String> = mutableStateOf("B")
-var StringUpUnit: MutableState<String> = mutableStateOf("B")
+var StringDownUnit: MutableState<String> = mutableStateOf(" Byte/s")
+var StringUpUnit: MutableState<String> = mutableStateOf(" Byte/s")
 
 lateinit var navHostController1: NavHostController
 lateinit var homeViewModel1: HomeViewModel

+ 103 - 0
app/src/main/java/com/vpn/fastestvpnservice/utils/VPNConnectionsUtil.kt

@@ -9,12 +9,15 @@ import android.content.ServiceConnection
 import android.content.pm.PackageManager
 import android.net.ConnectivityManager
 import android.net.NetworkCapabilities
+import android.net.TrafficStats
 import android.os.AsyncTask
 import android.os.Build
 import android.os.CountDownTimer
 import android.os.Handler
 import android.os.IBinder
+import android.os.Process
 import android.os.RemoteException
+import android.os.SystemClock
 import android.util.Log
 import android.widget.Toast
 import androidx.activity.ComponentActivity
@@ -29,6 +32,11 @@ import com.vpn.fastestvpnservice.constants.splitList
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
 import com.vpn.fastestvpnservice.helpers.UIHelper
 import com.vpn.fastestvpnservice.openVpnUtils.EncryptData
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.StringDown
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.StringDownUnit
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.StringUp
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.StringUpUnit
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.networkSpeed
 import com.vpn.fastestvpnservice.viewmodels.HomeViewModel
 import com.vpn.fastestvpnservice.widgets.SimpleAppWidget
 import com.wireguard.android.backend.Backend
@@ -56,6 +64,8 @@ import java.io.BufferedReader
 import java.io.InputStream
 import java.io.InputStreamReader
 import java.util.SortedSet
+import java.util.Timer
+import java.util.TimerTask
 import java.util.TreeSet
 
 class VPNConnectionsUtil: VpnStatus.StateListener {
@@ -83,6 +93,13 @@ class VPNConnectionsUtil: VpnStatus.StateListener {
     var pm: ProfileManager? = null
     var thread: Thread? = null
 
+    /* Network Stats - WG*/
+    private var lastUpdateTime = 0.0
+    private var lastTxBytes = 0.0
+    private var lastRxBytes = 0.0
+    private var finalTxBytes = 0.0
+    private var finalRxBytes = 0.0
+
     private lateinit var openVpnStateReceiver: OpenVpnStateReceiver
 
 
@@ -115,6 +132,11 @@ class VPNConnectionsUtil: VpnStatus.StateListener {
         Log.d("test_wg", "start vpn")
         Log.d("isConnect_State_vpn", "startVPN util")
 
+        StringDown.value = 0.0
+        StringUp.value = 0.0
+        StringDownUnit.value = " Byte/s"
+        StringUpUnit.value = " Byte/s"
+
         countDownTimer()
         try {
             if (CheckInternetConnection.getInternetConnection(context).isConnectedToInternet) {
@@ -353,6 +375,7 @@ class VPNConnectionsUtil: VpnStatus.StateListener {
                 if (isUp) {
                     App.tunnelStatus = Tunnel.State.UP
                     homeViewModel.setConnectState(App.CONNECTED)
+                    startTrafficMonitoring()
                     Log.d("test_wg", "tunnelStatus if = ${App.tunnelStatus}")
 
                     val widgetIntent = Intent(context, SimpleAppWidget::class.java)
@@ -688,6 +711,86 @@ class VPNConnectionsUtil: VpnStatus.StateListener {
         }
     }
 
+    private fun startTrafficMonitoring() {
+        lastUpdateTime = SystemClock.elapsedRealtime().toDouble()
+        lastTxBytes = TrafficStats.getUidTxBytes(Process.myUid()).toDouble()
+        lastRxBytes = TrafficStats.getUidRxBytes(Process.myUid()).toDouble()
+
+        Log.d(
+            "test_network_stats",
+            "STM: lastUpdateTime = $lastUpdateTime lastTxBytes = $lastTxBytes lastRxBytes = $lastRxBytes"
+        )
+
+        // Start monitoring using a timer or background thread
+        // For example:
+        val timer = Timer()
+        timer.schedule(object : TimerTask() {
+            override fun run() {
+//                Log.d("test_network_stats_DU", "isVpnActive: " + isVpnActive);
+                if (App.tunnelStatus == Tunnel.State.UP) {
+                    monitorVpnTraffic()
+                } else {
+                    if (basePreferenceHelper.getConnectState() == 0) {
+                        cancel()
+                    }
+                }
+            }
+        }, 0, 1000) // Update every 1 second
+    }
+
+    private fun monitorVpnTraffic() {
+        val currentTxBytes = TrafficStats.getUidTxBytes(Process.myUid()).toDouble()
+        val currentRxBytes = TrafficStats.getUidRxBytes(Process.myUid()).toDouble()
+
+        Log.d(
+            "test_network_stat_IKev2",
+            "MVT: currentTxBytes = $currentTxBytes currentRxBytes = $currentRxBytes"
+        )
+
+        val txBytes = currentTxBytes - lastTxBytes
+        val rxBytes = currentRxBytes - lastRxBytes
+
+        // Calculate VPN traffic statistics here
+        finalTxBytes = txBytes + finalTxBytes
+        finalRxBytes = rxBytes + finalRxBytes
+
+        var StringDown2 = 0.0
+        var StringUp2 = 0.0
+        var StringDownUnit = ""
+        var StringUpUnit = ""
+
+        if (finalTxBytes < 1000) {
+            StringUp2 = finalTxBytes
+            StringUpUnit = "Byte/s"
+        } else if ((finalTxBytes >= 1000) && (finalTxBytes <= 1000000)) {
+            StringUp2 = finalTxBytes / 1000
+            StringUpUnit = "KB/S"
+        } else {
+            StringUp2 = finalTxBytes / 1000000
+            StringUpUnit = "MB/S"
+        }
+
+        if (finalRxBytes < 1000) {
+            StringDown2 = finalRxBytes
+            StringDownUnit = "Byte/s"
+        } else if ((finalRxBytes >= 1000) && (finalRxBytes <= 1000000)) {
+            StringDown2 = finalRxBytes / 1000
+            StringDownUnit = "KB/S"
+        } else {
+            StringDown2 = finalRxBytes / 1000000
+            StringDownUnit = "MB/S"
+        }
+
+        Log.d("test_network_stat_final", "Down: $StringDown2 Up: $StringUp2")
+
+        networkSpeed.setNetworkSpeed(StringDown2, StringUp2, StringDownUnit, StringUpUnit)
+
+        // Update last update time and byte counts for next calculation
+        lastUpdateTime = SystemClock.elapsedRealtime().toDouble()
+        lastTxBytes = currentTxBytes
+        lastRxBytes = currentRxBytes
+    }
+
 
     fun onStopCallBack() {
         Log.d("test_home_resume", "onStopCallBack!")

+ 37 - 24
app/src/main/java/de/blinkt/openvpn/core/OpenVPNService.java

@@ -60,6 +60,7 @@ import com.vpn.fastestvpnservice.constants.AppConstant;
 import com.vpn.fastestvpnservice.constants.AppEnum;
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper;
 import com.vpn.fastestvpnservice.openVpnUtils.Data;
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.HomeScreenKt;
 
 import java.io.IOException;
 import java.lang.reflect.InvocationTargetException;
@@ -151,9 +152,11 @@ public class OpenVPNService extends VpnService implements StateListener, Callbac
     private Handler guiHandler;
     private Toast mlastToast;
     private Runnable mOpenVPNThread;
-    private long lastUpdateTime;
-    private long lastTxBytes;
-    private long lastRxBytes;
+    private double lastUpdateTime = 0.0;
+    private double lastTxBytes = 0.0;
+    private double lastRxBytes = 0.0;
+    private double finalTxBytes = 0.0;
+    private double finalRxBytes = 0.0;
 
     // From: http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java
     public static String humanReadableByteCount(long bytes, boolean speed, Resources res) {
@@ -296,37 +299,47 @@ public class OpenVPNService extends VpnService implements StateListener, Callbac
     }
 
     private void monitorVpnTraffic() {
-        long currentTxBytes = TrafficStats.getUidTxBytes(android.os.Process.myUid());
-        long currentRxBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid());
+        double currentTxBytes = TrafficStats.getUidTxBytes(android.os.Process.myUid());
+        double currentRxBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid());
 
-        Log.d("test_network_stats", "MVT: currentTxBytes = " + currentTxBytes + " currentRxBytes = " + currentRxBytes);
+        Log.d("test_network_stat_IKev2", "MVT: currentTxBytes = " + currentTxBytes + " currentRxBytes = " + currentRxBytes);
 
-        long elapsedTime = SystemClock.elapsedRealtime() - lastUpdateTime;
-        long txBytes = currentTxBytes - lastTxBytes;
-        long rxBytes = currentRxBytes - lastRxBytes;
-
-        Log.d("test_network_stats", "MVT: elapsedTime = " + elapsedTime + " txBytes = " + txBytes + " rxBytes = " + rxBytes);
+        double txBytes = currentTxBytes - lastTxBytes;
+        double rxBytes = currentRxBytes - lastRxBytes;
 
         // Calculate VPN traffic statistics here
 
-        String StringDown = "", StringUp = "";
-        if (txBytes < 1000) {
-            StringUp = txBytes + " byte/s";
-        } else if ((txBytes >= 1000) && (txBytes <= 1000_000)) {
-            StringUp = txBytes / 1000 + " kb/s";
+        finalTxBytes = txBytes + finalTxBytes;
+        finalRxBytes = rxBytes + finalRxBytes;
+
+        double StringDown2 = 0.0, StringUp2 = 0.0;
+        String StringDownUnit = "", StringUpUnit = "";
+
+        if (finalTxBytes < 1000) {
+            StringUp2 = finalTxBytes;
+            StringUpUnit = "Byte/s";
+        } else if ((finalTxBytes >= 1000) && (finalTxBytes <= 1000_000)) {
+            StringUp2 = finalTxBytes / 1000;
+            StringUpUnit = "KB/S";
         } else {
-            StringUp = txBytes / 1000_000 + " mb/s";
+            StringUp2 = finalTxBytes / 1000_000;
+            StringUpUnit = "MB/S";
         }
 
-        if (rxBytes < 1000) {
-            StringDown = rxBytes + " byte/s";
-        } else if ((rxBytes >= 1000) && (rxBytes <= 1000_000)) {
-            StringDown = rxBytes / 1000 + " kb/s";
+        if (finalRxBytes < 1000) {
+            StringDown2 = finalRxBytes;
+            StringDownUnit = "Byte/s";
+        } else if ((finalRxBytes >= 1000) && (finalRxBytes <= 1000_000)) {
+            StringDown2 = finalRxBytes / 1000;
+            StringDownUnit = "KB/S";
         } else {
-            StringDown = rxBytes / 1000_000 + " mb/s";
+            StringDown2 = finalRxBytes / 1000_000;
+            StringDownUnit = "MB/S";
         }
 
-        Log.d("test_network_stats_UD", "Down: " + StringDown + " Up: " + StringUp);
+        Log.d("test_network_stat_final", "Down: " + StringDown2 + " Up: " + StringUp2);
+
+        HomeScreenKt.getNetworkSpeed().setNetworkSpeed(StringDown2, StringUp2, StringDownUnit, StringUpUnit);
 
         // Update last update time and byte counts for next calculation
         lastUpdateTime = SystemClock.elapsedRealtime();
@@ -378,7 +391,7 @@ public class OpenVPNService extends VpnService implements StateListener, Callbac
 
         }
 
-//        startTrafficMonitoring();
+        startTrafficMonitoring();
         Date Today = Calendar.getInstance().getTime();
         SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
 

+ 5 - 13
app/src/main/java/org/strongswan/android/logic/CharonVpnService.java

@@ -148,11 +148,11 @@ public class CharonVpnService extends VpnService implements Runnable, VpnStateSe
     private Handler mHandler;
     private VpnStateService mService;
 
-    private double lastUpdateTime;
-    private double lastTxBytes;
-    private double lastRxBytes;
-    private double finalTxBytes = 0;
-    private double finalRxBytes = 0;
+    private double lastUpdateTime = 0.0;
+    private double lastTxBytes = 0.0;
+    private double lastRxBytes = 0.0;
+    private double finalTxBytes = 0.0;
+    private double finalRxBytes = 0.0;
 
     public static boolean isVpnActive = false;
     private final ServiceConnection mServiceConnection = new ServiceConnection() {
@@ -366,23 +366,15 @@ public class CharonVpnService extends VpnService implements Runnable, VpnStateSe
         return START_NOT_STICKY;
     }
 
-
-
     private void monitorVpnTraffic() {
         double currentTxBytes = TrafficStats.getUidTxBytes(android.os.Process.myUid());
         double currentRxBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid());
 
         Log.d("test_network_stat_IKev2", "MVT: currentTxBytes = " + currentTxBytes + " currentRxBytes = " + currentRxBytes);
 
-        double elapsedTime = SystemClock.elapsedRealtime() - lastUpdateTime;
         double txBytes = currentTxBytes - lastTxBytes;
         double rxBytes = currentRxBytes - lastRxBytes;
 
-//        long txBytes = currentTxBytes;
-//        long rxBytes = currentRxBytes;
-
-        Log.d("test_network_stat_IKev2", "MVT: elapsedTime = " + elapsedTime + " txBytes = " + txBytes + " rxBytes = " + rxBytes);
-
         // Calculate VPN traffic statistics here
 
 //        String StringDown = "", StringUp = "";