Parcourir la source

Created AutoConnectService for auto connect mechanism and vpn functionality even if the app is closed

Khubaib il y a 4 mois
Parent
commit
144a4a3993

+ 6 - 0
app/src/main/AndroidManifest.xml

@@ -223,6 +223,12 @@
             android:foregroundServiceType="specialUse" />
 
         <service
+            android:name=".utils.AutoConnectService"
+            android:enabled="true"
+            android:exported="true"
+            android:foregroundServiceType="specialUse" />
+
+        <service
             android:name=".fcm.NetworkJobService"
             android:permission="android.permission.BIND_JOB_SERVICE" />
 

+ 6 - 1
app/src/main/java/com/vpn/fastestvpnservice/fcm/WiFiMonitorService.java

@@ -30,13 +30,17 @@ import com.vpn.fastestvpnservice.R;
 import com.vpn.fastestvpnservice.beans.AutoConnectModel;
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper;
 import com.vpn.fastestvpnservice.screens.settingsScreenAll.AutoConnectScreenKt;
+import com.vpn.fastestvpnservice.utils.VPNConnectionsUtil;
 import com.vpn.fastestvpnservice.utils.WifiScanReceiver;
+import com.vpn.fastestvpnservice.viewmodels.HomeViewModel;
 
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Objects;
 import java.util.Timer;
 
+import de.blinkt.openvpn.core.App;
+
 public class WiFiMonitorService extends Service {
 
     private static final int WIFI_SCAN_INTERVAL = 10 * 1000; // 10 seconds
@@ -79,6 +83,8 @@ public class WiFiMonitorService extends Service {
     @Override
     public int onStartCommand(Intent intent, int flags, int startId) {
 
+        startForegroundNotification();
+
 //        timer = new Timer();
 //        timer.scheduleAtFixedRate(new TimerTask() {
 //            @Override
@@ -104,7 +110,6 @@ public class WiFiMonitorService extends Service {
 
         //        registerReceiver(wifiScanReceiver, intentFilter);
 
-        startForegroundNotification();
 
 //        if (Objects.equals(intent.getAction(), WIFI_STATE_CHANGED)) {
 //            Log.d("WIFI_STATE_CHANGED", "WIFI_STATE_CHANGED in WMS");

+ 4 - 3
app/src/main/java/com/vpn/fastestvpnservice/screens/settingsScreenAll/AutoConnectScreen.kt

@@ -61,6 +61,7 @@ import com.vpn.fastestvpnservice.interfaces.AutoConnectCallback
 import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.AddRowSettingsSmart
 import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.isSettingsViewModel
 import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.settingsViewModel
+import com.vpn.fastestvpnservice.utils.AutoConnectService
 import com.vpn.fastestvpnservice.viewmodels.SettingsViewModel
 
 var selectedSmart: MutableState<String> = mutableStateOf("")
@@ -159,14 +160,14 @@ fun AutoConnectScreen(navHostController: NavHostController) {
                         if (isSwitch) {
                             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                 Log.d("autoconnect_state", "startForegroundService")
-                                context.startForegroundService(Intent(context, WiFiMonitorService::class.java))
+                                context.startForegroundService(Intent(context, AutoConnectService::class.java))
                             }
                             else{
                                 Log.d("autoconnect_state", "startService")
-                                context.startService(Intent(context, WiFiMonitorService::class.java))
+                                context.startService(Intent(context, AutoConnectService::class.java))
                             }
                         } else {
-                            context.stopService(Intent(context, WiFiMonitorService::class.java))
+                            context.stopService(Intent(context, AutoConnectService::class.java))
                         }
                     },
                     modifier = Modifier.scale(0.8F),

+ 255 - 0
app/src/main/java/com/vpn/fastestvpnservice/utils/AutoConnectService.kt

@@ -0,0 +1,255 @@
+package com.vpn.fastestvpnservice.utils
+
+import android.Manifest
+import android.app.Notification
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.Service
+import android.content.ComponentName
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.ServiceConnection
+import android.content.pm.PackageManager
+import android.net.ConnectivityManager
+import android.net.wifi.ScanResult
+import android.net.wifi.SupplicantState
+import android.net.wifi.WifiManager
+import android.os.Binder
+import android.os.Build
+import android.os.CountDownTimer
+import android.os.IBinder
+import android.util.Log
+import androidx.core.app.ActivityCompat
+import com.vpn.fastestvpnservice.R
+import com.vpn.fastestvpnservice.beans.AutoConnectModel
+import com.vpn.fastestvpnservice.constants.smartConnect
+import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.homeViewModel1
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.isHomeViewModel1
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.isVpnConnectionsUtil
+import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.vpnConnectionsUtil
+import com.vpn.fastestvpnservice.screens.settingsScreenAll.autoConnectCallback
+import com.vpn.fastestvpnservice.utils.WireGuardService.IkevConnectionStatesReceiverWidget
+import de.blinkt.openvpn.VpnProfile
+import de.blinkt.openvpn.core.App
+import de.blinkt.openvpn.core.ConfigParser
+import de.blinkt.openvpn.core.IOpenVPNServiceInternal
+import de.blinkt.openvpn.core.ProfileManager
+import java.io.BufferedReader
+import java.io.InputStream
+
+class AutoConnectService : Service() {
+
+    private var wifiScanReceiver: WifiScanReceiver? = null
+    private var wifiManager: WifiManager? = null
+    val NOTIFICATION_ID: Int = 2
+    private var intentFilter: IntentFilter? = null
+
+    private val binder: IBinder = LocalBinder()
+
+    inner class LocalBinder : Binder() {
+        val service: AutoConnectService
+            get() = this@AutoConnectService
+    }
+
+    var countDownTimer: CountDownTimer? = null
+
+//    /*IKEV2*/
+//    private lateinit var ikevConnectionStatesReceiver: IkevConnectionStatesReceiverWidget
+
+    /*TCP, UDP*/
+    var mService: IOpenVPNServiceInternal? = null
+    var inputStream: InputStream? = null
+    var bufferedReader: BufferedReader? = null
+    var cp: ConfigParser? = null
+    var vp: VpnProfile? = null
+    var pm: ProfileManager? = null
+
+    private val mConnection: ServiceConnection = object : ServiceConnection {
+
+        override fun onServiceConnected(className: ComponentName, service: IBinder) {
+
+            App.mService = IOpenVPNServiceInternal.Stub.asInterface(service)
+            Log.d("wg test s tcp wid", "onServiceConnected widget ${App.mService}")
+
+        }
+
+        override fun onServiceDisconnected(arg0: ComponentName) {
+            Log.d("wg test s tcp", "onServiceDisconnected")
+
+            App.mService = null
+        }
+    }
+
+    companion object {
+        /*IKEV2*/
+        lateinit var ikevConnectionStatesReceiver: IkevConnectionStatesReceiverWidget
+    }
+
+    override fun onCreate() {
+        super.onCreate()
+
+        wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
+        wifiScanReceiver = WifiScanReceiver()
+        intentFilter = IntentFilter()
+        intentFilter?.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
+
+        registerReceiver(wifiScanReceiver, intentFilter)
+    }
+
+    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+
+        startForegroundNotification()
+
+        return START_STICKY
+    }
+
+    private fun startForegroundNotification() {
+        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+            val channelId = "FastestVPN_Foreground_Wifi"
+            val channel =
+                NotificationChannel(channelId, "FastestVPN", NotificationManager.IMPORTANCE_LOW)
+            val notificationManager = getSystemService(
+                NotificationManager::class.java
+            )
+
+            notificationManager.createNotificationChannel(channel)
+            val notification: Notification.Builder = Notification.Builder(
+                applicationContext, channelId
+            )
+                .setContentTitle("Your connection is secured")
+                .setContentText("Auto-connect feature will automatically detect network changes as set in the app settings.")
+                .setColor(applicationContext.resources.getColor(R.color.blue_text))
+                .setSmallIcon(R.drawable.ic_logo_notify)
+            startForeground(1, notification.build())
+        }
+    }
+
+    fun getConnectedWifiService() {
+        Log.d("AutoConnectService", "Started")
+
+        if (ActivityCompat.checkSelfPermission(
+                applicationContext,
+                Manifest.permission.ACCESS_FINE_LOCATION
+            ) != PackageManager.PERMISSION_GRANTED ||
+            ActivityCompat.checkSelfPermission(
+                applicationContext,
+                Manifest.permission.ACCESS_COARSE_LOCATION
+            ) != PackageManager.PERMISSION_GRANTED
+        ) {
+            return
+        }
+
+        // currently commenting below ...
+        val basePreferenceHelper = BasePreferenceHelper(applicationContext)
+        wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
+        val scanResults = wifiManager?.scanResults
+        Log.d("AutoConnectService", "Job scanResults + " + scanResults?.size)
+
+        val nonZeroList: MutableList<ScanResult> = ArrayList()
+
+        if (!scanResults.isNullOrEmpty()) {
+            Log.d("AutoConnectService 1", scanResults.size.toString() + "")
+                nonZeroList.addAll(scanResults)
+        } else {
+        }
+
+        Log.d("AutoConnectService in", "Inside")
+
+        //        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
+        if (wifiManager?.isWifiEnabled == true) {
+            Log.d("AutoConnectService", "isWifiEnabled")
+            val connectivityManager =
+                applicationContext.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
+
+            val activeNetwork = connectivityManager.activeNetworkInfo
+
+            if (activeNetwork != null && activeNetwork.isConnected && activeNetwork.type == ConnectivityManager.TYPE_WIFI) {
+                val wifiInfo = wifiManager?.connectionInfo
+
+                Log.d("AutoConnectService", "activeNetwork = $activeNetwork")
+
+                if (wifiInfo != null && wifiInfo.supplicantState == SupplicantState.COMPLETED) {
+                    val connectedWifiSsid = wifiInfo.ssid.replace("\"", "")
+
+                    Log.d("AutoConnectServicecssid", "wifiInfo.getSSID() = " + wifiInfo.ssid)
+
+                    val autoConnectWifiList = basePreferenceHelper.getAutoConnectList()
+                    val wifiList = ArrayList<AutoConnectModel>()
+
+                    Log.d("AutoConnectService", "connectedWifiSsid = $connectedWifiSsid")
+                    Log.d(
+                        "AutoConnectService",
+                        "Before autoConnectWifiList = " + (autoConnectWifiList?.size
+                            ?: 0)
+                    )
+
+                    if (autoConnectWifiList != null && !autoConnectWifiList.isEmpty()) {
+                        wifiList.addAll(autoConnectWifiList)
+
+                        var isConnectedSsidInList = false
+                        for ((wifiName) in wifiList) {
+                            if (wifiName == connectedWifiSsid) {
+                                isConnectedSsidInList = true
+                                break
+                            }
+                        }
+
+                        if (!isConnectedSsidInList && !connectedWifiSsid.isEmpty()) {
+                            wifiList.add(0, AutoConnectModel(connectedWifiSsid, false))
+                        }
+                    } else {
+                        if (!connectedWifiSsid.isEmpty()) {
+                            wifiList.add(AutoConnectModel(connectedWifiSsid, false))
+                        }
+                    }
+
+                    Log.d("AutoConnectService", "wifiList = " + wifiList.size)
+                    Log.d("AutoConnectService", "wifiList = $wifiList")
+
+                    autoConnectCallback.autoConnectList(wifiList)
+                    autoConnectCallback.autoConnectedWifi(connectedWifiSsid)
+
+                    val isTrustedWifiConnected = wifiList.any { it.wifiName == connectedWifiSsid && it.isAdded }
+
+                    val isConnect = basePreferenceHelper.getConnectState()
+
+                    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 -> {}
+                    }
+
+                    Log.d("AutoConnectService", "smartServer = ${smartServer?.server_name} & $selectedSmartList")
+                    basePreferenceHelper.setConnectedServer(smartServer)
+
+                    if (isTrustedWifiConnected && isConnect == App.CONNECTED) {
+                        Log.d("AutoConnectService", "Disconnect VPN")
+                    }
+                    else if (!isTrustedWifiConnected && isConnect == App.DISCONNECTED) {
+                        Log.d("AutoConnectService", "Connect VPN")
+                    }
+                    else if (isTrustedWifiConnected && isConnect == App.CONNECTING) {
+                        Log.d("AutoConnectService", "Connecting VPN")
+                    }
+                }
+            }
+        }
+
+    }
+
+
+    override fun onBind(intent: Intent?): IBinder? {
+        return binder
+    }
+}

+ 25 - 7
app/src/main/java/com/vpn/fastestvpnservice/utils/WifiScanReceiver.java

@@ -14,15 +14,13 @@ import android.net.wifi.WifiManager;
 import android.os.Build;
 import android.os.IBinder;
 import android.util.Log;
+
 import androidx.core.app.NotificationCompat;
 
 import com.vpn.fastestvpnservice.MainActivity;
 import com.vpn.fastestvpnservice.R;
-import com.vpn.fastestvpnservice.fcm.NetworkJobService;
 import com.vpn.fastestvpnservice.fcm.WiFiMonitorService;
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper;
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.SettingsScreenKt;
-import com.vpn.fastestvpnservice.viewmodels.SettingsViewModel;
 
 import java.util.Objects;
 
@@ -32,6 +30,7 @@ public class WifiScanReceiver extends BroadcastReceiver {
 
     Context context;
     private WiFiMonitorService wiFiMonitorService;
+    private AutoConnectService autoConnectService;
     private boolean isBound = false;
 
     private ServiceConnection serviceConnection = new ServiceConnection() {
@@ -39,16 +38,28 @@ public class WifiScanReceiver extends BroadcastReceiver {
         public void onServiceConnected(ComponentName name, IBinder service) {
             Log.d("WifiScanReceiver", "onServiceConnected");
 
-            WiFiMonitorService.LocalBinder binder = (WiFiMonitorService.LocalBinder) service;
-            wiFiMonitorService = binder.getService();
+
+            AutoConnectService.LocalBinder binder = (AutoConnectService.LocalBinder) service;
+            autoConnectService = binder.getService();
             isBound = true;
 
-            wiFiMonitorService.getConnectedWifiService();
+            autoConnectService.getConnectedWifiService();
 
             if (isBound) {
                 context.unbindService(this);
                 isBound = false;
             }
+
+//            WiFiMonitorService.LocalBinder binder = (WiFiMonitorService.LocalBinder) service;
+//            wiFiMonitorService = binder.getService();
+//            isBound = true;
+//
+//            wiFiMonitorService.getConnectedWifiService();
+//
+//            if (isBound) {
+//                context.unbindService(this);
+//                isBound = false;
+//            }
         }
 
         @Override
@@ -80,9 +91,16 @@ public class WifiScanReceiver extends BroadcastReceiver {
 
 //                SettingsScreenKt.settingsViewModel.getConnectedWifi();
 
-                Intent wifiIntent1 = new Intent(context, WiFiMonitorService.class);
+
+
+//                Intent wifiIntent1 = new Intent(context, WiFiMonitorService.class);
+//                context.bindService(wifiIntent1, serviceConnection, Context.BIND_AUTO_CREATE);
+
+                Intent wifiIntent1 = new Intent(context, AutoConnectService.class);
                 context.bindService(wifiIntent1, serviceConnection, Context.BIND_AUTO_CREATE);
 
+
+
 //            NetworkJobService.scheduleJob(context); // now commenting, will use later...
             }
         }

+ 1 - 1
app/src/main/java/com/vpn/fastestvpnservice/utils/WireGuardService.kt

@@ -28,7 +28,6 @@ import com.vpn.fastestvpnservice.constants.AppEnum
 import com.vpn.fastestvpnservice.constants.splitList
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
 import com.vpn.fastestvpnservice.openVpnUtils.EncryptData
-import com.vpn.fastestvpnservice.screens.bottomNavBarScreens.homeViewModel1
 import com.vpn.fastestvpnservice.widgets.SimpleAppWidget
 import com.wireguard.android.backend.GoBackend
 import com.wireguard.android.backend.Tunnel
@@ -99,6 +98,7 @@ class WireGuardService : Service(), VpnStatus.StateListener {
 
 
     }
+
     fun connectVpn() {
 
         basePreferenceHelper = BasePreferenceHelper(applicationContext)