Prechádzať zdrojové kódy

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

Khubaib 8 mesiacov pred
rodič
commit
6159ca2c54

+ 1 - 1
app/src/main/java/com/vpn/fastestvpnservice/interfaces/NetworkSpeedCallback.kt

@@ -3,5 +3,5 @@ package com.vpn.fastestvpnservice.interfaces
 import androidx.compose.runtime.Composable
 
 interface NetworkSpeedCallback {
-    fun setNetworkSpeed(down: String, up: String)
+    fun setNetworkSpeed(down: Double, up: Double, downUnit: String, upUnit: String)
 }

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

@@ -4,6 +4,7 @@ import android.app.Activity
 import android.content.Context
 import android.content.Intent
 import android.content.res.Configuration
+import android.icu.text.DecimalFormat
 import android.os.Handler
 import android.util.Log
 import androidx.activity.ComponentActivity
@@ -27,6 +28,8 @@ import androidx.compose.foundation.layout.height
 import androidx.compose.foundation.layout.padding
 import androidx.compose.foundation.layout.size
 import androidx.compose.foundation.layout.wrapContentHeight
+import androidx.compose.foundation.layout.wrapContentSize
+import androidx.compose.foundation.layout.wrapContentWidth
 import androidx.compose.foundation.shape.CircleShape
 import androidx.compose.foundation.shape.RoundedCornerShape
 import androidx.compose.foundation.text.ClickableText
@@ -91,6 +94,7 @@ import com.vpn.fastestvpnservice.interfaces.ServerCallbacks
 import com.vpn.fastestvpnservice.screens.serverListViewModelSplash
 import com.vpn.fastestvpnservice.sealedClass.Screen
 import com.vpn.fastestvpnservice.ui.theme.customTypography
+import com.vpn.fastestvpnservice.ui.theme.customTypography2
 import com.vpn.fastestvpnservice.utils.Utils
 import com.vpn.fastestvpnservice.utils.VPNConnectionsUtil
 import com.vpn.fastestvpnservice.utils.isTablet
@@ -99,6 +103,7 @@ import com.vpn.fastestvpnservice.viewmodels.ServerListViewModel
 import com.vpn.fastestvpnservice.widgets.SimpleAppWidget
 import com.wireguard.android.backend.GoBackend
 import de.blinkt.openvpn.core.App
+import java.util.Locale
 
 lateinit var act: ComponentActivity
 var isServerDialog: MutableState<Boolean> = mutableStateOf(false)
@@ -107,8 +112,11 @@ var serverObj: MutableState<Server> = mutableStateOf(Server())
 var protocolObj: MutableState<Protocol> = mutableStateOf(
     Protocol(AppEnum.WG_PROTOCOL.title,AppEnum.WG_PROTOCOL.key, 1)
 )
-var StringDown: MutableState<String> = mutableStateOf("")
-var StringUp: MutableState<String> = 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")
 
 lateinit var navHostController1: NavHostController
 lateinit var homeViewModel1: HomeViewModel
@@ -228,9 +236,12 @@ lateinit var vpnConnectionsUtil: VPNConnectionsUtil
  }
 
 val networkSpeed = object : NetworkSpeedCallback {
-    override fun setNetworkSpeed(down: String, up: String) {
+    override fun setNetworkSpeed(down: Double, up: Double, downUnit: String, upUnit: String) {
         StringDown.value = down
         StringUp.value = up
+
+        StringDownUnit.value = downUnit
+        StringUpUnit.value = upUnit
         Log.d("setNetworkSpeed", "Down: ${StringDown.value} Up: ${StringUp.value}")
     }
 }
@@ -620,59 +631,61 @@ fun Home(
                 verticalArrangement = Arrangement.Top
             ) {
 
-                Box(
-                    modifier = Modifier
-                        .fillMaxWidth(fraction = if (isTablet()) 0.5f else 1f)
-                        .padding(horizontal = 20.dp)
-                        .padding(vertical = 5.dp)
-                        .height(120.dp)
-                        .border(
-                            border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
-                            shape = RoundedCornerShape(28.dp)
-                        )
-                        .background(
-                            shape = RoundedCornerShape(28.dp),
-                            color = MaterialTheme.colorScheme.onBackground
-                        )
-                        .align(Alignment.CenterHorizontally)
+                if (isConnect != App.CONNECTED)
+                {
+                    Box(
+                        modifier = Modifier
+                            .fillMaxWidth(fraction = if (isTablet()) 0.5f else 1f)
+                            .padding(horizontal = 20.dp)
+                            .padding(vertical = 5.dp)
+                            .height(120.dp)
+                            .border(
+                                border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
+                                shape = RoundedCornerShape(28.dp)
+                            )
+                            .background(
+                                shape = RoundedCornerShape(28.dp),
+                                color = MaterialTheme.colorScheme.onBackground
+                            )
+                            .align(Alignment.CenterHorizontally)
                         ,
-                ) {
-                    AddRowSmart(navHostController, basePreferenceHelper, context, isTablet())
-                    var smartServer = basePreferenceHelper.getSmartServerObject()
-                    val recommended = basePreferenceHelper.getRecommendedServerObject()
-                    val selectedSmartList = basePreferenceHelper.getSmartList()
-                    when(selectedSmartList) {
-                        smartConnect[0] -> {
-                            smartServer = basePreferenceHelper.getRecommendedServerObject()
-                        }
-                        smartConnect[1] -> {
-                            smartServer = basePreferenceHelper.getSmartServerObject() ?: recommended
-                        }
-                        smartConnect[2] -> {
-                            smartServer = basePreferenceHelper.getSmartServerObject() ?: recommended
+                    ) {
+                        AddRowSmart(navHostController, basePreferenceHelper, context, isTablet())
+                        var smartServer = basePreferenceHelper.getSmartServerObject()
+                        val recommended = basePreferenceHelper.getRecommendedServerObject()
+                        val selectedSmartList = basePreferenceHelper.getSmartList()
+                        when(selectedSmartList) {
+                            smartConnect[0] -> {
+                                smartServer = basePreferenceHelper.getRecommendedServerObject()
+                            }
+                            smartConnect[1] -> {
+                                smartServer = basePreferenceHelper.getSmartServerObject() ?: recommended
+                            }
+                            smartConnect[2] -> {
+                                smartServer = basePreferenceHelper.getSmartServerObject() ?: recommended
+                            }
+                            else -> {}
                         }
-                        else -> {}
-                    }
-                    Button(
-                        onClick = {
-                            basePreferenceHelper.setSmartServerObject(smartServer)
+                        Button(
+                            onClick = {
+                                basePreferenceHelper.setSmartServerObject(smartServer)
 //                            basePreferenceHelper.setConnectedServer(smartServer)
 
-                            if (isConnect == App.CONNECTED) {
-                                Log.d("isConnect_State_vpn", "stopVPN")
-                                val lastServer = basePreferenceHelper.getConnectedServer()
+                                if (isConnect == App.CONNECTED) {
+                                    Log.d("isConnect_State_vpn", "stopVPN")
+                                    val lastServer = basePreferenceHelper.getConnectedServer()
 
-                                if (lastServer?.id != smartServer?.id) {
-                                    isServerDialog.value = true
-                                    if (smartServer != null) {
-                                        serverObj.value = smartServer
-                                    }
+                                    if (lastServer?.id != smartServer?.id) {
+                                        isServerDialog.value = true
+                                        if (smartServer != null) {
+                                            serverObj.value = smartServer
+                                        }
 //                                    basePreferenceHelper.setConnectedServer(smartServer)
 
-                                }
-                                else {
-                                    vpnConnectionsUtil.stopVpn()
-                                }
+                                    }
+                                    else {
+                                        vpnConnectionsUtil.stopVpn()
+                                    }
 
 
 //                                vpnConnectionsUtil.stopVpn()
@@ -680,70 +693,180 @@ fun Home(
 //                                    vpnConnectionsUtil.startVpn()
 //                                }, 500)
 //                                homeViewModel.getIp()
-                            }
-                            else if (isConnect == App.CONNECTING) {
-                                vpnConnectionsUtil.stopVpn()
-                            }
-                            else if (isConnect == App.DISCONNECTED) {
-                                Log.d("isConnect_State_vpn", "startVPN")
-                                basePreferenceHelper.setConnectedServer(smartServer)
-                                if (smartServer != null) {
-                                    serverListViewModel.setRecentlyConnectedServer(smartServer)
                                 }
-                                vpnConnectionsUtil.startVpn()
-                            }
+                                else if (isConnect == App.CONNECTING) {
+                                    vpnConnectionsUtil.stopVpn()
+                                }
+                                else if (isConnect == App.DISCONNECTED) {
+                                    Log.d("isConnect_State_vpn", "startVPN")
+                                    basePreferenceHelper.setConnectedServer(smartServer)
+                                    if (smartServer != null) {
+                                        serverListViewModel.setRecentlyConnectedServer(smartServer)
+                                    }
+                                    vpnConnectionsUtil.startVpn()
+                                }
 
 //                                navHostController.navigate(
 //                                    BottomBarScreen.Settings.route
 //                                )
 //                                BottomBarScreen.Settings.isTrue = true
 
-                        },
-                        modifier = Modifier
-                            .padding(start = 14.dp, end = 14.dp, bottom = 12.dp, top = 16.dp)
-                            .align(Alignment.BottomCenter)
-                            .background(colorResource(id = R.color.transparent))
-                            .fillMaxWidth()
-                            .height(40.dp),
-                        shape = RoundedCornerShape(16.dp),
-                        colors = ButtonDefaults.buttonColors(
-                            contentColor = colorResource(id = R.color.white),
-                            containerColor = colorResource(id = R.color.blue_text),
-                        ),
-                    ) {
-                        Text(
-                            text = "Smart Connect",
-                            style = MaterialTheme.typography.customTypography.labelLarge.copy(
-                                fontSize = if (isTablet()) 21.sp else 18.sp
+                            },
+                            modifier = Modifier
+                                .padding(start = 14.dp, end = 14.dp, bottom = 12.dp, top = 16.dp)
+                                .align(Alignment.BottomCenter)
+                                .background(colorResource(id = R.color.transparent))
+                                .fillMaxWidth()
+                                .height(40.dp),
+                            shape = RoundedCornerShape(16.dp),
+                            colors = ButtonDefaults.buttonColors(
+                                contentColor = colorResource(id = R.color.white),
+                                containerColor = colorResource(id = R.color.blue_text),
                             ),
-                            modifier = Modifier.background(Color.Transparent)
-                        )
+                        ) {
+                            Text(
+                                text = "Smart Connect",
+                                style = MaterialTheme.typography.customTypography.labelLarge.copy(
+                                    fontSize = if (isTablet()) 21.sp else 18.sp
+                                ),
+                                modifier = Modifier.background(Color.Transparent)
+                            )
+                        }
                     }
-                }
 
-                /* Select Server Box*/
+                    /* Select Server Box*/
 //                if (isConnect != App.CONNECTED) { }
 
 //                Spacer(modifier = Modifier.weight(1f))
 
-                Box(
-                    modifier = Modifier
-                        .fillMaxWidth(fraction = if (isTablet()) 0.5f else 1f)
-                        .padding(horizontal = 20.dp, vertical = 5.dp)
-                        .padding(top = 0.dp)
-                        .height(70.dp)
-                        .border(
-                            border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
-                            shape = RoundedCornerShape(28.dp)
-                        )
-                        .background(
-                            shape = RoundedCornerShape(28.dp),
-                            color = MaterialTheme.colorScheme.onBackground
-                        )
-                        .align(Alignment.CenterHorizontally),
-                    contentAlignment = Alignment.CenterStart,
-                ) {
-                    AddRowSelectServer(navHostController, isTablet())
+                    Box(
+                        modifier = Modifier
+                            .fillMaxWidth(fraction = if (isTablet()) 0.5f else 1f)
+                            .padding(horizontal = 20.dp, vertical = 5.dp)
+                            .padding(top = 0.dp)
+                            .height(70.dp)
+                            .border(
+                                border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
+                                shape = RoundedCornerShape(28.dp)
+                            )
+                            .background(
+                                shape = RoundedCornerShape(28.dp),
+                                color = MaterialTheme.colorScheme.onBackground
+                            )
+                            .align(Alignment.CenterHorizontally),
+                        contentAlignment = Alignment.CenterStart,
+                    ) {
+                        AddRowSelectServer(navHostController, isTablet())
+                    }
+                }
+                else {
+                    Box(
+                        modifier = Modifier
+                            .fillMaxWidth()
+                            .padding(16.dp)
+                            .padding(top = 0.dp)
+                            .height(110.dp)
+//                    .border(
+//                        border = BorderStroke(0.dp, Color.Blue),
+//                        shape = RoundedCornerShape(28.dp)
+//                    )
+                            .background(
+                                color = Color.Transparent
+                            ),
+                    ) {
+                        Row(
+                            modifier = Modifier
+                                .padding(0.dp)
+                                .background(Color.Transparent),
+                            horizontalArrangement = Arrangement.SpaceAround,
+                            verticalAlignment = Alignment.CenterVertically
+                        ) {
+                            Surface(
+                                modifier = Modifier
+                                    .weight(1f)
+                                    .background(Color.Transparent)
+                                    .fillMaxHeight()
+                                    .padding(end = 5.dp),
+                                shape = RoundedCornerShape(24.dp)
+
+                            ) {
+                                Column(
+                                    modifier = Modifier
+                                        .background(Color.White),
+                                    verticalArrangement = Arrangement.SpaceEvenly,
+                                    horizontalAlignment = Alignment.CenterHorizontally
+                                ) {
+                                    Image(
+                                        painter = painterResource(id = R.drawable.greenarrow3x),
+                                        contentDescription = "Green Arrow",
+                                        modifier = Modifier
+                                            .size(30.dp)
+                                    )
+                                    Text(
+                                        text = "Download",
+                                        style = MaterialTheme.typography.customTypography.displayMedium,
+                                        modifier = Modifier.alpha(0.6F)
+                                    )
+                                    Row(
+                                        horizontalArrangement = Arrangement.SpaceAround,
+                                        verticalAlignment = Alignment.CenterVertically
+                                    ) {
+                                        Text(
+                                            text = String.format(Locale.US, "%.2f", StringDown.value),
+                                            style = MaterialTheme.typography.customTypography.displayLarge
+                                        )
+                                        Text(
+                                            text = "  ${StringDownUnit.value}",
+                                            style = MaterialTheme.typography.customTypography2.labelSmall,
+                                            modifier = Modifier.alpha(0.5F)
+                                        )
+                                    }
+                                }
+                            }
+                            Surface(
+                                modifier = Modifier
+                                    .weight(1f)
+                                    .background(Color.Transparent)
+                                    .fillMaxHeight()
+                                    .padding(start = 5.dp),
+                                shape = RoundedCornerShape(24.dp)
+                            ) {
+                                Column(
+                                    modifier = Modifier
+                                        .background(Color.White),
+                                    verticalArrangement = Arrangement.SpaceEvenly,
+                                    horizontalAlignment = Alignment.CenterHorizontally
+                                ) {
+                                    Image(
+                                        painter = painterResource(id = R.drawable.yellowarrow3x),
+                                        contentDescription = "Green Arrow",
+                                        modifier = Modifier
+                                            .size(30.dp)
+                                    )
+                                    Text(
+                                        text = "Upload",
+                                        style = MaterialTheme.typography.customTypography.displayMedium,
+                                        modifier = Modifier.alpha(0.6F)
+                                    )
+                                    Row(
+                                        horizontalArrangement = Arrangement.SpaceAround,
+                                        verticalAlignment = Alignment.CenterVertically
+                                    ) {
+                                        Text(
+                                            text = String.format(Locale.US,"%.2f", StringUp.value),
+                                            style = MaterialTheme.typography.customTypography.displayLarge
+
+                                        )
+                                        Text(
+                                            text = "  ${StringUpUnit.value}",
+                                            style = MaterialTheme.typography.customTypography2.labelSmall,
+                                            modifier = Modifier.alpha(0.5F)
+                                        )
+                                    }
+                                }
+                            }
+                        }
+                    }
                 }
             }
         }

+ 56 - 22
app/src/main/java/org/strongswan/android/logic/CharonVpnService.java

@@ -148,9 +148,11 @@ public class CharonVpnService extends VpnService implements Runnable, VpnStateSe
     private Handler mHandler;
     private VpnStateService mService;
 
-    private long lastUpdateTime;
-    private long lastTxBytes;
-    private long lastRxBytes;
+    private double lastUpdateTime;
+    private double lastTxBytes;
+    private double lastRxBytes;
+    private double finalTxBytes = 0;
+    private double finalRxBytes = 0;
 
     public static boolean isVpnActive = false;
     private final ServiceConnection mServiceConnection = new ServiceConnection() {
@@ -257,7 +259,7 @@ public class CharonVpnService extends VpnService implements Runnable, VpnStateSe
                     profile.setVpnType(VpnType.IKEV2_EAP);
                     profile.setName(server_name);
 
-//                    startTrafficMonitoring();
+                    startTrafficMonitoring();
 
                     UiModeManager uiModeManager = (UiModeManager) getApplicationContext().getSystemService(UI_MODE_SERVICE);
                     List<String> splitList = Arrays.asList("All apps use the VPN", "Only allow selected apps to use the vpn",
@@ -367,38 +369,70 @@ public class CharonVpnService extends VpnService implements Runnable, VpnStateSe
 
 
     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_stat_IKev2", "MVT: currentTxBytes = " + currentTxBytes + " currentRxBytes = " + currentRxBytes);
 
-        long elapsedTime = SystemClock.elapsedRealtime() - lastUpdateTime;
-        long txBytes = currentTxBytes - lastTxBytes;
-        long rxBytes = currentRxBytes - lastRxBytes;
+        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 = "";
-        if (txBytes < 1000) {
-            StringUp = txBytes + " byte/s";
-        } else if ((txBytes >= 1000) && (txBytes <= 1000_000)) {
-            StringUp = txBytes / 1000 + " kb/s";
+//        String StringDown = "", StringUp = "";
+//        if (txBytes < 1000) {
+//            StringUp = txBytes + " byte/s";
+//        } else if ((txBytes >= 1000) && (txBytes <= 1000_000)) {
+//            StringUp = txBytes / 1000 + " kb/s";
+//        } else {
+//            StringUp = txBytes / 1000_000 + " mb/s";
+//        }
+//
+//        if (rxBytes < 1000) {
+//            StringDown = rxBytes + " byte/s";
+//        } else if ((rxBytes >= 1000) && (rxBytes <= 1000_000)) {
+//            StringDown = rxBytes / 1000 + " kb/s";
+//        } else {
+//            StringDown = rxBytes / 1000_000 + " mb/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_stat_IKev2_DU", "Down: " + StringDown + " Up: " + StringUp);
-        HomeScreenKt.getNetworkSpeed().setNetworkSpeed(StringDown, 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();