浏览代码

TV work completed

Khubaib 1 年之前
父节点
当前提交
6ee1c9e422

+ 1 - 1
.idea/deploymentTargetDropDown.xml

@@ -18,7 +18,7 @@
               </deviceKey>
             </Target>
           </runningDeviceTargetSelectedWithDropDown>
-          <timeTargetWasSelectedWithDropDown value="2024-04-27T12:27:53.515658773Z" />
+          <timeTargetWasSelectedWithDropDown value="2024-04-28T18:09:55.102187023Z" />
         </State>
       </entry>
     </value>

+ 1 - 1
app/src/main/AndroidManifest.xml

@@ -37,7 +37,7 @@
         android:label="@string/app_name"
         android:roundIcon="@drawable/app_logo_round"
         android:supportsRtl="true"
-        android:theme="@style/Theme.AppCompat.NoActionBar"
+        android:theme="@style/Theme.AppCompat.Light.NoActionBar"
         android:usesCleartextTraffic="true"
         tools:targetApi="31">
         <activity

+ 0 - 1
app/src/main/java/com/vpn/fastestvpnservice/MainActivity.kt

@@ -213,7 +213,6 @@ open class MainActivity : DockActivity(), ConnectivityReceiver.ConnectivityRecei
     }
 
     override fun onNetworkConnectionChanged(isConnected: Boolean) {
-        TODO("Not yet implemented")
     }
 }
 

+ 4 - 6
app/src/main/java/com/vpn/fastestvpnservice/activities/GuidedActivity.java

@@ -36,7 +36,7 @@ import com.vpn.fastestvpnservice.helpers.FragmentNavigator;
 import com.vpn.fastestvpnservice.interfaces.CallBacks;
 import com.vpn.fastestvpnservice.interfaces.OnBackPressedOnTV;
 import com.vpn.fastestvpnservice.interfaces.VPNConnectionCallBacks;
-import com.vpn.fastestvpnservice.utils.VPNConnectionsUtil;
+import com.vpn.fastestvpnservice.utils.VPNConnectionUtilsTV;
 import com.vpn.fastestvpnservice.viewmodels.HomeViewModel;
 
 import java.util.ArrayList;
@@ -44,8 +44,6 @@ import java.util.List;
 import java.util.Objects;
 
 import de.blinkt.openvpn.core.App;
-import kotlinx.coroutines.CoroutineScope;
-import kotlinx.coroutines.Job;
 
 public class GuidedActivity extends FragmentActivity {
 
@@ -164,7 +162,7 @@ public class GuidedActivity extends FragmentActivity {
             implements CallBacks, VPNConnectionCallBacks, OnBackPressedOnTV {   // Protocol
 
         public BasePreferenceHelper prefhelper;
-        VPNConnectionsUtil vpnConnectionsUtil;
+        VPNConnectionUtilsTV vpnConnectionsUtil;
         HomeViewModel homeViewModel;
 
 
@@ -187,7 +185,7 @@ public class GuidedActivity extends FragmentActivity {
             String descProtocol = prefhelper.getProtocol().getFull_name();
 //            CoroutineScope scope = new Job();
 //            homeViewModel = HomeViewModel(requireContext(), )
-//            vpnConnectionsUtil = new VPNConnectionsUtil(requireActivity(), this, );
+            vpnConnectionsUtil = new VPNConnectionUtilsTV(requireActivity(), this);
 
             String description = getString(R.string.first_breadcum_fragment);
 
@@ -322,7 +320,7 @@ public class GuidedActivity extends FragmentActivity {
                     new Handler().postDelayed(new Runnable() {
                         @Override
                         public void run() {
-                            vpnConnectionsUtil.startVpn();
+                            vpnConnectionsUtil.connectVpn();
                         }
                     }, 500);
 

+ 55 - 32
app/src/main/java/com/vpn/fastestvpnservice/activities/HomeActivityTV.kt

@@ -2,6 +2,7 @@ package com.vpn.fastestvpnservice.activities
 
 import android.app.Activity
 import android.app.Dialog
+import android.content.DialogInterface
 import android.content.Intent
 import android.graphics.Color
 import android.graphics.drawable.ColorDrawable
@@ -9,24 +10,23 @@ import android.location.Location
 import android.os.Bundle
 import android.os.Handler
 import android.os.Looper
+import android.util.Log
 import android.view.View
 import android.view.Window
 import android.view.animation.Animation
 import android.view.animation.AnimationUtils
 import android.widget.TextView
 import android.widget.Toast
-import androidx.activity.enableEdgeToEdge
 import androidx.appcompat.app.AppCompatActivity
-import androidx.core.view.ViewCompat
-import androidx.core.view.WindowInsetsCompat
 import androidx.lifecycle.Observer
 import com.google.android.material.snackbar.Snackbar
+import com.vpn.fastestvpnservice.MainActivity
 import com.vpn.fastestvpnservice.R
 import com.vpn.fastestvpnservice.beans.Protocol
 import com.vpn.fastestvpnservice.beans.Server
 import com.vpn.fastestvpnservice.constants.AppEnum
 import com.vpn.fastestvpnservice.databinding.ActivityHomeTvBinding
-import com.vpn.fastestvpnservice.fragments.LoginFragment
+import com.vpn.fastestvpnservice.dialogs.DialogFactory
 import com.vpn.fastestvpnservice.fragments.TvHomeFragment
 import com.vpn.fastestvpnservice.fragments.TvServerListFragment
 import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
@@ -35,6 +35,7 @@ import com.vpn.fastestvpnservice.interfaces.VPNConnectionCallBacks
 import com.vpn.fastestvpnservice.utils.SnackBarUtils
 import com.vpn.fastestvpnservice.utils.StaticMethods
 import com.vpn.fastestvpnservice.utils.Utils
+import com.vpn.fastestvpnservice.utils.VPNConnectionUtilsTV
 import com.vpn.fastestvpnservice.utils.VPNConnectionsUtil
 import com.vpn.fastestvpnservice.viewmodels.HomeViewModel
 import com.vpn.fastestvpnservice.viewmodels.ProfileViewModel
@@ -42,7 +43,6 @@ import com.vpn.fastestvpnservice.viewmodels.ServerListViewModel
 import com.wireguard.android.backend.GoBackend
 import de.blinkt.openvpn.core.App
 import kotlinx.coroutines.CoroutineScope
-import kotlinx.coroutines.Job
 import kotlinx.coroutines.MainScope
 
 class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
@@ -53,7 +53,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
     lateinit var homeViewModel: HomeViewModel
     lateinit var profileViewModel: ProfileViewModel
     var serverobj: Server? = null
-    lateinit var vpnConnectionsUtil: VPNConnectionsUtil
+    lateinit var vpnConnectionsUtil: VPNConnectionUtilsTV
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
 //        enableEdgeToEdge()
@@ -72,7 +72,8 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
         profileViewModel = ProfileViewModel()
         serverViewModel = ServerListViewModel(baseContext)
         homeViewModel = HomeViewModel(baseContext, scope)
-        vpnConnectionsUtil = VPNConnectionsUtil(baseContext, this, homeViewModel)
+        vpnConnectionsUtil = VPNConnectionUtilsTV(this, this)
+        vpnConnectionsUtil.initUI()
 
         if (StaticMethods.isTV(this)) {
             tvHomeBinding.ivConnect.background = resources.getDrawable(R.drawable.connect_btn_state)
@@ -81,6 +82,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
 
         }
 
+        MainActivity.callBacks = this
         clickListeners()
         viewModelObserver()
         showServers()
@@ -101,7 +103,8 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
     fun clickListeners() {
         tvHomeBinding.ivConnect.setOnClickListener {
             prefHelper.setServerObject(serverobj)
-//            vpnConnectionsUtil.connectVpn()
+            Log.d("test_tv_connection", "ivConnect click => ${serverobj?.server_name}")
+            vpnConnectionsUtil.connectVpn()
         }
 
         tvHomeBinding.tvLogoutTv?.setOnClickListener {
@@ -194,6 +197,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
                 prefHelper.getServerData().get(0).servers!!
             )
         }
+        prefHelper.setServerObject(filterServerByConnectionCount)
 
 //        callBacks?.onServerSelected(filterServerByConnectionCount)
 
@@ -210,7 +214,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
                     tvHomeBinding.tvCountry?.text ="${it.city}, ${it.country}"
                 }
                 tvHomeBinding.cardCountryImg?.visibility = View.VISIBLE
-                tvHomeBinding.ivCountry?.setImageDrawable(
+                tvHomeBinding.ivCountryImg?.setImageDrawable(
                     Utils.getCountryFlag(baseContext, it.countryCode?.toLowerCase().toString())
                 )
             }
@@ -312,23 +316,23 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
         serverobj?.let {
             if (vpnConnectionsUtil.isVPNConnected()) {
                 if (serverobj?.id != server.id) {
-//                    DialogFactory.createDialog(requireActivity(),
-//                        serverobj?.server_name,
-//                        server.server_name,
-//                        object : DialogInterface.OnClickListener {
-//                            override fun onClick(dialog: DialogInterface?, which: Int) {
-//                                setData(server)
-//                                vpnConnectionsUtil.stopVpn()
-//                                Handler().postDelayed(Runnable {
-//                                    tvHomeBinding.ivConnect?.performClick()
-//                                }, 500)
-//                            }
-//                        },
-//                        object : DialogInterface.OnClickListener {
-//                            override fun onClick(dialog: DialogInterface?, which: Int) {
-//                               dialog?.dismiss()
-//                            }
-//                        })
+                    DialogFactory.createDialog(this,
+                        serverobj?.server_name,
+                        server.server_name,
+                        object : DialogInterface.OnClickListener {
+                            override fun onClick(dialog: DialogInterface?, which: Int) {
+                                setData(server)
+                                vpnConnectionsUtil.stopVpn()
+                                Handler().postDelayed(Runnable {
+                                    vpnConnectionsUtil.connectVpn()
+                                }, 500)
+                            }
+                        },
+                        object : DialogInterface.OnClickListener {
+                            override fun onClick(dialog: DialogInterface?, which: Int) {
+                               dialog?.dismiss()
+                            }
+                        })
                 } else {
                     setData(server)
                 }
@@ -339,7 +343,8 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
 
                 vpnConnectionsUtil.stopVpn()
                 Handler().postDelayed(Runnable {
-                    tvHomeBinding.ivConnect?.performClick()
+                      vpnConnectionsUtil.connectVpn()
+//                    tvHomeBinding.ivConnect?.performClick()
                 }, 500)
 
 //                if (fragmentNavigator.topFragment is TvHomeFragment) {
@@ -355,9 +360,10 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
 
     fun setData(server: Server) {
         serverobj = server
-
-        tvHomeBinding.tvServer?.text = server.server_name ?: server.name
-        tvHomeBinding.ivCountry?.setImageDrawable(
+        prefHelper.setServerObject(server)
+        tvHomeBinding.tvServer.text = server.server_name ?: server.name
+        Log.d("HomeActivityTV_Log", "${server.server_name} ${server.iso}")
+        tvHomeBinding.ivCountryServer.setImageDrawable(
             Utils.getCountryFlag(baseContext, server.iso?.toLowerCase().toString())
         )
     }
@@ -374,12 +380,28 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
     override fun onResume() {
         super.onResume()
 
+        Log.d("HomeActivityTV_Log", "onResume")
+//        SnackBarUtils.showSnackBar(
+//            findViewById(android.R.id.content),
+//            getString(R.string.account_not_subscribed), Snackbar.LENGTH_LONG)
+
         prefHelper.getProduct()?.identifier?.let {
             if (it == AppEnum.FREE.key) {
-//                SnackBarUtils.showSnackBar(view, getString(R.string.account_not_subscribed), Snackbar.LENGTH_LONG)
+                SnackBarUtils.showSnackBar(
+                    findViewById(android.R.id.content), getString(R.string.account_not_subscribed), Snackbar.LENGTH_LONG)
             }
         }
 
+//        var filterServerByConnectionCount = Server()
+//        if (prefHelper.getServerObject() != null) {
+//            filterServerByConnectionCount = prefHelper.getServerObject()!!
+//        } else {
+//            filterServerByConnectionCount = serverViewModel.filterServerByConnectionCount(
+//                prefHelper.getServerData().get(0).servers!!
+//            )
+//        }
+//        prefHelper.setServerObject(filterServerByConnectionCount)
+
         try {
             App.backend?.runningTunnelNames
         } catch (e: Exception) {
@@ -426,6 +448,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
         }
 
         prefHelper.getServerObject().let { server ->
+            Log.d("HomeActivityTV_Log", "server: conn: ${server?.server_name} ${server?.iso}")
             tvHomeBinding.tvIp?.let {
                 it.text = "IP: ${server?.ip}"
                 if (server!!.city == null)
@@ -436,7 +459,7 @@ class HomeActivityTV : AppCompatActivity(), VPNConnectionCallBacks, CallBacks {
                     tvHomeBinding.tvCountry.text ="${server.city}, ${server?.country}"
                 }
                 tvHomeBinding.cardCountryImg.visibility = View.VISIBLE
-                tvHomeBinding.ivCountry.setImageDrawable(
+                tvHomeBinding.ivCountryImg?.setImageDrawable(
                     Utils.getCountryFlag(baseContext, server?.iso?.toLowerCase().toString())
                 )
             }

+ 162 - 0
app/src/main/java/com/vpn/fastestvpnservice/dialogs/DialogFactory.java

@@ -0,0 +1,162 @@
+package com.vpn.fastestvpnservice.dialogs;
+
+import android.app.Activity;
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.ProgressDialog;
+import android.content.ActivityNotFoundException;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.net.Uri;
+import android.widget.EditText;
+
+
+public class DialogFactory {
+    private static final int i = -1;
+
+    public static Dialog createProgressDialog(Activity activity, String title, String loadingMessage) {
+        ProgressDialog prDialog = new ProgressDialog(activity);
+        prDialog.setTitle(title);
+        prDialog.setMessage(loadingMessage);
+        return prDialog;
+    }
+
+    public static Dialog createQuitDialog(Activity activity, DialogInterface.OnClickListener dialogPositive, int messageId) {
+
+
+//		AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.Theme_MaterialComponents_Light_Dialog));
+        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+
+//		AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+//		builder.setIcon(android.R.drawable.ic_dialog_alert)
+//				.setTitle(android.R.string.dialog_alert_title)
+        builder.setMessage(messageId).setCancelable(true).setPositiveButton(android.R.string.yes, dialogPositive).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
+
+            @Override
+            public void onClick(DialogInterface dialog, int which) {
+                dialog.dismiss();
+
+            }
+        });
+        return builder.create();
+
+    }
+
+    public static void showPDfFileDialog(final Uri file, final Context context) {
+
+        Intent intent;
+        intent = new Intent(Intent.ACTION_VIEW);
+        intent.setDataAndType(file, "application/pdf");
+        try {
+            context.startActivity(intent);
+        } catch (ActivityNotFoundException e) {
+            // No application to view, ask to download one
+            AlertDialog.Builder builder = new AlertDialog.Builder(context);
+            builder.setTitle("No BaseApplication Found");
+            builder.setMessage("Download one from Android Market?");
+            builder.setPositiveButton("Yes, Please", new DialogInterface.OnClickListener() {
+                @Override
+                public void onClick(DialogInterface dialog, int which) {
+                    Intent marketIntent = new Intent(Intent.ACTION_VIEW);
+                    marketIntent.setData(Uri.parse("market://details?id=com.adobe.reader"));
+                    context.startActivity(marketIntent);
+                }
+            });
+            builder.setNegativeButton("No, Thanks", null);
+            builder.create().show();
+        }
+    }
+
+    public static Dialog createSimpleDialog(Activity activity, DialogInterface.OnClickListener dialogPositive, int messageId, int titleId) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+        builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(messageId).setCancelable(true).setPositiveButton(android.R.string.yes, dialogPositive).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
+
+            @Override
+            public void onClick(DialogInterface dialog, int which) {
+                dialog.dismiss();
+
+            }
+        });
+        return builder.create();
+
+    }
+
+    public static Dialog createSingleButtonDialog(Activity activity, DialogInterface.OnClickListener dialogPositive, String messageId) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+        builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(messageId).setCancelable(true).setPositiveButton(android.R.string.yes, dialogPositive);
+
+        return builder.create();
+
+    }
+
+    public static Dialog createMessageDialog(Activity activity, DialogInterface.OnClickListener dialogPositive, CharSequence message) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+        builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setCancelable(false).setMessage(message).setPositiveButton(android.R.string.yes, dialogPositive);
+        return builder.create();
+
+    }
+
+    public static Dialog createMessageDialog2(Activity activity, DialogInterface.OnClickListener dialogPositive, CharSequence message, String titleId) {
+        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+        builder.setIcon(android.R.drawable.ic_dialog_alert).setTitle(android.R.string.dialog_alert_title).setMessage(message).setCancelable(true).setPositiveButton("Yes", dialogPositive).setNegativeButton("No", new DialogInterface.OnClickListener() {
+
+            @Override
+            public void onClick(DialogInterface dialog, int which) {
+                dialog.dismiss();
+
+            }
+        });
+        return builder.create();
+
+    }
+
+    public static Dialog createInputDialog(Activity activity, DialogInterface.OnClickListener dialogPositive, DialogInterface.OnClickListener dialogNegative, String title, String message) {
+
+        AlertDialog.Builder alert = new AlertDialog.Builder(activity);
+        alert.setIcon(android.R.drawable.ic_dialog_alert);
+        alert.setTitle(title);
+        alert.setMessage(message);
+        final EditText input = new EditText(activity);
+        alert.setView(input);
+
+        alert.setPositiveButton("Yes", dialogPositive);
+
+        alert.setNegativeButton("No", dialogNegative);
+
+        return alert.create();
+
+    }
+
+    public static void createDialog(Activity activity, String previous, String newServer, DialogInterface.OnClickListener dialogPositive, DialogInterface.OnClickListener dialogNegative) {
+        AlertDialog.Builder alert = new AlertDialog.Builder(activity);
+        alert.setTitle("Confirm");
+        alert.setMessage("Are you sure to switch from " + previous + " to " + newServer + "");
+
+//        alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
+//            @Override
+//            public void onClick(DialogInterface dialog, int which) {
+//                dialog.dismiss();
+//            }
+//        });
+
+        alert.setPositiveButton("Yes", dialogPositive);
+        alert.setNegativeButton("No", dialogNegative);
+        alert.create().show();
+    }
+
+
+    // public static SweetAlertDialog showSweetLoader(Context context,
+    // int dialogtype, String title) {
+    //
+    // SweetAlertDialog pDialog = new SweetAlertDialog(context, dialogtype);
+    // pDialog.setTitleText(title);
+    //
+    // pDialog.setCancelable(false);
+    //
+    // pDialog.show();
+    // return pDialog;
+    // }
+
+
+}

+ 837 - 0
app/src/main/java/com/vpn/fastestvpnservice/utils/VPNConnectionUtilsTV.kt

@@ -0,0 +1,837 @@
+package com.vpn.fastestvpnservice.utils
+
+import android.app.Activity
+import android.content.BroadcastReceiver
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.content.ServiceConnection
+import android.content.pm.PackageManager
+import android.net.ConnectivityManager
+import android.net.NetworkCapabilities
+import android.os.AsyncTask
+import android.os.Build
+import android.os.CountDownTimer
+import android.os.IBinder
+import android.os.RemoteException
+import android.util.Log
+import androidx.localbroadcastmanager.content.LocalBroadcastManager
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.vpn.fastestvpnservice.MainActivity
+import com.vpn.fastestvpnservice.R
+import com.vpn.fastestvpnservice.constants.AppConstant
+import com.vpn.fastestvpnservice.constants.AppEnum
+import com.vpn.fastestvpnservice.helpers.BasePreferenceHelper
+import com.vpn.fastestvpnservice.helpers.UIHelper
+import com.vpn.fastestvpnservice.interfaces.VPNConnectionCallBacks
+import com.vpn.fastestvpnservice.openVpnUtils.EncryptData
+import com.vpn.fastestvpnservice.widgets.SimpleAppWidget
+import com.wireguard.android.backend.Backend
+import com.wireguard.android.backend.GoBackend
+import com.wireguard.android.backend.Tunnel
+import com.wireguard.config.Config
+import com.wireguard.config.InetEndpoint
+import com.wireguard.config.InetNetwork
+import com.wireguard.config.Interface
+import com.wireguard.config.Peer
+import de.blinkt.openvpn.LaunchVPN
+import de.blinkt.openvpn.VpnProfile
+import de.blinkt.openvpn.core.App
+import de.blinkt.openvpn.core.ConfigParser
+import de.blinkt.openvpn.core.ConnectionStatus
+import de.blinkt.openvpn.core.IOpenVPNServiceInternal
+import de.blinkt.openvpn.core.OpenVPNService
+import de.blinkt.openvpn.core.ProfileManager
+import de.blinkt.openvpn.core.VpnStatus
+import org.json.JSONObject
+import org.strongswan.android.logic.CharonVpnService
+import org.strongswan.android.ui.VpnProfileControlActivity
+import wireguard.WgTunnel
+import java.io.BufferedReader
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.util.SortedSet
+import java.util.TreeSet
+
+class VPNConnectionUtilsTV: VpnStatus.StateListener {
+
+    var basePreferenceHelper: BasePreferenceHelper
+    var vpnConnectionCallBacks: VPNConnectionCallBacks
+    var countDownTimer: CountDownTimer? = null
+
+    /*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
+    var thread: Thread? = null
+
+    /*IKEV2*/
+    private lateinit var ikevConnectionStatesReceiver: IkevConnectionStatesReceiver
+
+    companion object {
+        var backend: Backend? = null
+        var peerBuilder = Peer.Builder()
+        var tunnel: Tunnel = WgTunnel()
+    }
+
+    /*WireGuard*/
+
+    private val mConnection: ServiceConnection = object : ServiceConnection {
+        override fun onServiceConnected(className: ComponentName, service: IBinder) {
+            App.mService = IOpenVPNServiceInternal.Stub.asInterface(service)
+            Log.d("test_openvpn", "onServiceConnected: ${App.mService}")
+        }
+
+        override fun onServiceDisconnected(arg0: ComponentName) {
+            App.mService = null
+            Log.d("test_openvpn", "onServiceDisconnected: ${App.mService}")
+        }
+    }
+
+    var context: Activity
+    var dnswg: String = ""
+
+    constructor(context: Activity, vpnConnectionCallBacks: VPNConnectionCallBacks) {
+
+        this.context = context
+        this.basePreferenceHelper = BasePreferenceHelper(context)
+        this.vpnConnectionCallBacks = vpnConnectionCallBacks
+        backend = GoBackend(context)
+
+//        App.backend = this.backend
+    }
+
+    fun connectVpn() {
+        if (App.connection_status == App.CONNECTION_STATE_DISCONNECTED) {
+            startVpn()
+        }
+        else if (App.connection_status == App.CONNECTION_STATE_CONNECTED ||
+            App.connection_status == App.CONNECTION_STATE_CONNECTED_2 ||
+            App.connection_status == App.CONNECTION_STATE_CONNECTING) {
+            stopVpn()
+        }
+        else if (App.connection_status == App.CONNECTION_STATE_SERVER_NOT_RESPONDING) {
+            Log.d("Auto test connect", "ACTION_VPN_SERVER_NOT_RESPONDING connectVpn")
+
+//            stopVpn()
+            startTcpUDP()
+        }
+        else if (App.connection_status == App.CONNECTION_STATE_UP_WG) {
+            stopVpn()
+        }
+        else if (App.connection_status == App.CONNECTION_STATE_DOWN_WG) {
+            startVpn()
+        }
+    }
+
+    fun startVpn() {
+        Log.d("testing_wg_on_tv", "startVpn Called TV")
+
+        countDownTimer()
+        try {
+            if (CheckInternetConnection.getInternetConnection(context).isConnectedToInternet) {
+
+                if (basePreferenceHelper.getProtocol().title.contentEquals(AppEnum.IKEV2_PROTOCOL.key))
+                {
+
+                    basePreferenceHelper.getServerObject().let { server ->
+
+                        /*Connect IKEV2*/
+
+                        val intent = Intent(context, VpnProfileControlActivity::class.java)
+                        App.connection_status = App.CONNECTION_STATE_CONNECTING
+                        val widgetIntent1 = Intent(context, SimpleAppWidget::class.java)
+                        widgetIntent1.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+                        context.sendBroadcast(widgetIntent1)
+                        intent.action = VpnProfileControlActivity.START_PROFILE
+                        intent.putExtra(VpnProfileControlActivity.EXTRA_VPN_PROFILE_ID, server?.id)
+                        intent.putExtra(AppConstant.SERVER, Gson().toJson(server))
+                        intent.putExtra("username", basePreferenceHelper.getUser()?.userinfo?.email)
+                        intent.putExtra(
+                            "password", basePreferenceHelper.getPassword()
+                        )
+                        context.startActivity(intent)
+
+                    }
+                }
+                else if (basePreferenceHelper.getProtocol().title.toLowerCase()
+                        .contentEquals(AppEnum.WG_PROTOCOL.key.toLowerCase())
+                ) {
+
+                    /*Connect Wire-Guard*/
+                    MainActivity.isWGDown = true
+                    vpnWireGuardPermission(true)
+
+
+                } else {
+
+                    /*Connect UDP / TCP*/
+                    startTcpUDP()
+
+                }
+            }
+
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun startTcpUDP() {
+        Log.d("Auto test connect", "ACTION_VPN_SERVER_NOT_RESPONDING startTcpUDP")
+
+
+        /*Connect UDP,TCP*/
+        App.connection_status = App.CONNECTION_STATE_CONNECTING
+        val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+        widgetIntent.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+        context.sendBroadcast(widgetIntent)
+        App.isShowNotify = true
+        countDownTimer?.start()
+
+        try {
+            inputStream = null
+            bufferedReader = null
+            inputStream = getJsonFileDetails()
+            assert(inputStream != null)
+            bufferedReader =
+                BufferedReader(InputStreamReader(inputStream /*, Charset.forName("UTF-8")*/))
+            cp = ConfigParser(context)
+            cp!!.parseConfig(bufferedReader)
+            vp = cp!!.convertProfile()
+
+            ///////////////// openvpn split tunneling start /////////////////
+            val type = object : TypeToken<SortedSet<String?>?>() {}.type
+
+            val selectedApps = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledApps(), type
+            )
+            val selectedAppsNoVpn = Gson().fromJson<SortedSet<String>>(
+                basePreferenceHelper.getSplitTunneledAppsNotAllow(), type
+            )
+
+            if (StaticMethods.isTV(context))                              // TV
+            {
+                val listEnable = basePreferenceHelper.getEnableTvAppsSplit()
+
+                if (listEnable?.size == 0) {
+                    Log.d("TCP/UDP Split Tunneling", "All apps")
+                }
+                else
+                {
+                    val appPackageName: SortedSet<String> = TreeSet()
+                    if (listEnable != null){
+                        for (i in listEnable.indices) {
+                            appPackageName.add(listEnable[i].appPackageName)
+                        }
+                    }
+
+                    if (appPackageName.size > 0)
+                    {
+                        for (app in appPackageName)
+                        {
+                            try {
+                                vp?.mAllowedAppsVpn?.add(app)
+                                Log.d("packages Vpn", app)
+                            } catch (e: PackageManager.NameNotFoundException) {
+                                e.printStackTrace()
+                            }
+                        }
+                    }
+                }
+            }
+            else{                                                           // Android
+//                basePreferenceHelper.getRadioBtnSplitPos().let {
+//                    when (it) {
+//                        0 -> {
+//                        }
+//                        1 -> {
+//                            if (selectedApps != null && selectedApps.size > 0) {
+//                                for (app in selectedApps) {
+//                                    try {
+//                                        vp?.mAllowedAppsVpn?.add(app)
+//                                        Log.d("packages Vpn", app)
+//                                    } catch (e: PackageManager.NameNotFoundException) {
+//                                        e.printStackTrace()
+//                                    }
+//                                }
+//                            }
+//                        }
+//                        2 -> {
+//                            if (selectedAppsNoVpn != null && selectedAppsNoVpn.size > 0) {
+//                                for (app in selectedAppsNoVpn) {
+//                                    try {
+//                                        vp?.mAllowedAppsVpn?.add(app)
+//                                        Log.d("packages NoVpn", app)
+//                                    } catch (e: PackageManager.NameNotFoundException) {
+//                                        e.printStackTrace()
+//                                    }
+//                                }
+//                            }
+//                        }
+//                    }
+//                }
+            }
+
+            ///////////////// openvpn split tunneling end /////////////////
+            vp?.mAllowedAppsVpnAreDisallowed = false
+            val En = EncryptData()
+            val AppDetailsValues = En.decrypt(basePreferenceHelper.getAppDetails())
+
+            val json_response = JSONObject(AppDetailsValues)
+            val jsonArray = json_response.getJSONArray("blocked")
+            for (i in 0 until jsonArray.length()) {
+                val json_object = jsonArray.getJSONObject(i)
+                vp?.mAllowedAppsVpn?.add(json_object.getString("app"))
+                Log.e("packages end", json_object.getString("app"))
+            }
+
+            vp?.mName = Build.MODEL
+            vp?.mUsername = basePreferenceHelper.getUser()?.userinfo?.email
+            vp?.mPassword = basePreferenceHelper.getPassword()
+            pm = ProfileManager.getInstance(context)
+            pm?.addProfile(vp)
+            pm?.saveProfileList(context)
+            pm?.saveProfile(context, vp)
+            vp = pm?.getProfileByName(Build.MODEL)
+            val intent = Intent(context, LaunchVPN::class.java)
+            intent.putExtra(LaunchVPN.EXTRA_KEY, vp?.uuid.toString())
+            intent.action = Intent.ACTION_MAIN
+            context.startActivity(intent)
+        }
+        catch (e: Exception) {
+            e.printStackTrace()
+            Log.d("test_openvpn", "catch = ${e.printStackTrace()}")
+        }
+    }
+
+    fun stopVpn() {
+        try {
+            /*Disconnect IKEV2*/
+
+//            Log.d("App.connection stop", App.connection_status.toString())
+
+            Log.d("App stop ikev2", "1")
+            val intent = Intent(context, VpnProfileControlActivity::class.java)
+            Log.d("App stop ikev2", "2")
+            intent.action = VpnProfileControlActivity.DISCONNECT
+            Log.d("App stop ikev2", "3")
+            context.startActivity(intent)
+            Log.d("App stop ikev2", "4")
+
+            /*Disconnect TCP,UDP*/
+            App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+            val widgetIntent1 = Intent(context, SimpleAppWidget::class.java)
+            widgetIntent1.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+            context.sendBroadcast(widgetIntent1)
+
+            App.isShowNotify = false
+            OpenVPNService.abortConnectionVPN = true
+            ProfileManager.setConntectedVpnProfileDisconnected(context)
+            if (App.mService != null) {
+                Log.d("test_openvpn", "if => ${App.mService}")
+                try {
+                    Log.d("test_openvpn", "try => ${App.mService}")
+                    App.mService!!.stopVPN(false)
+                } catch (e: RemoteException) {
+                    e.printStackTrace()
+                }
+                try {
+                    pm = ProfileManager.getInstance(context)
+                    vp = pm?.getProfileByName(Build.MODEL)
+                    pm?.removeProfile(context, vp)
+                } catch (e: Exception) {
+                    e.printStackTrace()
+                }
+            }
+
+            /*Disconnect Wireguard*/
+            if (basePreferenceHelper.getProtocol().title.toLowerCase()
+                    .contentEquals(AppEnum.WG_PROTOCOL.key.toLowerCase())
+            )
+            {
+                vpnWireGuardPermission(false)
+
+            }
+
+            val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+            widgetIntent.action = SimpleAppWidget.ACTION_STOP_SERVICE
+            context.sendBroadcast(widgetIntent)
+
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun vpnWireGuardPermission(isUp: Boolean) {
+
+        if (App.backend != null)
+        {
+            App.backend?.runningTunnelNames
+        }
+        else {
+            val back = GoBackend(context)
+            App.setBackend(back)
+            App.backend = App.getBackend()
+        }
+
+//        Log.d("testing_wg_on_tv WG f", App.backend.toString())
+
+        try{
+            val intentPrepare: Intent = GoBackend.VpnService.prepare(context)
+            if (intentPrepare != null) {
+
+                context.startActivityForResult(intentPrepare, 552)
+            }
+        }catch (e :Exception){
+            vpnWireGuard(isUp)
+        }
+    }
+
+    fun vpnWireGuard(isUp: Boolean) {
+//        Log.d("testing_wg_on_tv", "vpnWireGuard Called TV")
+
+        if (basePreferenceHelper.getAdBlockState())
+        {
+            dnswg = "10.8.8.8"
+        }
+        else {
+            dnswg = "10.9.9.9"
+        }
+
+        val interfaceBuilder: Interface.Builder? = Interface.Builder()
+
+        AsyncTask.execute {
+            try {
+                val type = object : TypeToken<SortedSet<String?>?>() {}.type
+                val selectedApps = Gson().fromJson<SortedSet<String>>(
+                    basePreferenceHelper.getSplitTunneledApps(), type
+                )
+                val selectedAppsNoVpn = Gson().fromJson<SortedSet<String>>(
+                    basePreferenceHelper.getSplitTunneledAppsNotAllow(), type
+                )
+
+                if (isUp) {
+//                    App.connection_status = App.CONNECTION_STATE_CONNECTED
+                    App.connection_status = App.CONNECTION_STATE_UP_WG
+                    App.tunnelStatus = Tunnel.State.UP
+
+                    val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_CONNECT_VPN
+                    context.sendBroadcast(widgetIntent)
+                } else {
+//                    App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+                    App.connection_status = App.CONNECTION_STATE_DOWN_WG
+                    App.tunnelStatus = Tunnel.State.DOWN
+
+//                    val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+//                    widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+//                    context.sendBroadcast(widgetIntent)
+
+                    if (MainActivity.isWGDown)
+                    {
+                        vpnConnectionCallBacks.onGetIp()
+                        MainActivity.isWGDown = false
+                    }
+                }
+
+                if (StaticMethods.isTV(context))
+                {
+                    try {
+                        App.backend?.runningTunnelNames
+                    } catch (e: Exception) {
+                        val back = GoBackend(context)
+                        App.setBackend(back)
+                        App.backend = App.getBackend()
+                    }
+                    val listEnable = basePreferenceHelper.getEnableTvAppsSplit()
+
+//                    Log.d("testing_wg_on_tv WG s", "${App.backend.toString()} , ${App.getTunnel()} + ${App.tunnelStatus} + ${App.peerBuilder}")
+
+                    if (listEnable?.size == 0)
+                    {
+                        App.backend?.setState(
+                            App.getTunnel(), App.tunnelStatus, Config.Builder().setInterface(
+                                interfaceBuilder!!.addAddress(InetNetwork.parse(basePreferenceHelper.getWireGuard()?.ip + "/32"))
+                                    .parsePrivateKey(basePreferenceHelper.getWireGuard()?.key)
+                                    .parseDnsServers(dnswg)
+                                    .build()
+                            ).addPeer(
+                                App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+                                    .setEndpoint(InetEndpoint.parse(basePreferenceHelper.getServerObject()?.dns + ":51820"))
+                                    .parsePublicKey(basePreferenceHelper.getServerObject()?.wg_key).build()
+                            ).build()
+                        )
+
+
+                    }
+                    else{
+                        val tempEnabledList = ArrayList<String>()
+
+                        listEnable?.forEachIndexed { index, tvSplitTunneling ->
+                            tempEnabledList.add(index, tvSplitTunneling.appPackageName)
+                        }
+
+                        App.backend?.setState(
+                            App.getTunnel(), App.tunnelStatus, Config.Builder().setInterface(
+                                interfaceBuilder!!.addAddress(InetNetwork.parse(basePreferenceHelper.getWireGuard()?.ip + "/32"))
+                                    .parsePrivateKey(basePreferenceHelper.getWireGuard()?.key)
+                                    .parseDnsServers(dnswg)
+                                    .includeApplications(tempEnabledList)
+                                    .build()
+                            ).addPeer(
+                                App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+                                    .setEndpoint(InetEndpoint.parse(basePreferenceHelper.getServerObject()?.dns + ":51820"))
+                                    .parsePublicKey(basePreferenceHelper.getServerObject()?.wg_key).build()
+                            ).build()
+                        )
+                    }
+                }
+                else
+                {
+//                    try {
+//                        App.backend?.runningTunnelNames
+//                    } catch (e: Exception) {
+//                        val back = GoBackend(context)
+//                        App.setBackend(back)
+//                        App.backend = App.getBackend()
+//                    }
+//                    basePreferenceHelper.getRadioBtnSplitPos().let {
+//                        when(it){
+//                            0 -> {
+////                                Log.d("testing_wg_on_tv WG e", "${App.backend.toString()} , ${App.getTunnel()} + ${App.tunnelStatus} + ${App.peerBuilder}")
+//
+//                                App.backend?.setState(
+//                                    App.getTunnel(), App.tunnelStatus, Config.Builder().setInterface(
+//                                        interfaceBuilder!!.addAddress(InetNetwork.parse(basePreferenceHelper.getWireGuard()?.ip + "/32"))
+//                                            .parsePrivateKey(basePreferenceHelper.getWireGuard()?.key)
+//                                            .parseDnsServers(dnswg)
+//                                            .build()
+//                                    ).addPeer(
+//                                        App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+//                                            .setEndpoint(InetEndpoint.parse(basePreferenceHelper.getServerObject()?.dns + ":51820"))
+//                                            .parsePublicKey(basePreferenceHelper.getServerObject()?.wg_key).build()
+//                                    ).build()
+//                                )
+//
+//
+//                            }
+//                            1 -> {
+//                                App.backend?.setState(
+//                                    App.getTunnel(), App.tunnelStatus, Config.Builder().setInterface(
+//                                        interfaceBuilder!!.addAddress(InetNetwork.parse(basePreferenceHelper.getWireGuard()?.ip + "/32"))
+//                                            .parsePrivateKey(basePreferenceHelper.getWireGuard()?.key)
+//                                            .parseDnsServers(dnswg)
+//                                            .includeApplications(selectedApps)
+//                                            .build()
+//                                    ).addPeer(
+//                                        App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+//                                            .setEndpoint(InetEndpoint.parse(basePreferenceHelper.getServerObject()?.dns + ":51820"))
+//                                            .parsePublicKey(basePreferenceHelper.getServerObject()?.wg_key).build()
+//                                    ).build()
+//                                )
+//                            }
+//                            2 -> {
+//                                App.backend?.setState(
+//                                    App.getTunnel(), App.tunnelStatus, Config.Builder().setInterface(
+//                                        interfaceBuilder!!.addAddress(InetNetwork.parse(basePreferenceHelper.getWireGuard()?.ip + "/32"))
+//                                            .parsePrivateKey(basePreferenceHelper.getWireGuard()?.key)
+//                                            .parseDnsServers(dnswg)
+//                                            .includeApplications(selectedAppsNoVpn)
+//                                            .build()
+//                                    ).addPeer(
+//                                        App.peerBuilder.addAllowedIp(InetNetwork.parse("0.0.0.0/0"))
+//                                            .setEndpoint(InetEndpoint.parse(basePreferenceHelper.getServerObject()?.dns + ":51820"))
+//                                            .parsePublicKey(basePreferenceHelper.getServerObject()?.wg_key).build()
+//                                    ).build()
+//                                )
+//                            }
+//                            else -> {}
+//                        }
+//                    }
+                }
+
+            } catch (e: java.lang.Exception) {
+                e.printStackTrace()
+            }
+        }
+    }
+
+    fun countDownTimer() {
+        countDownTimer = object : CountDownTimer(32000, 1000) {
+            override fun onTick(millisUntilFinished: Long) {
+                if (App.connection_status == App.CONNECTION_STATE_CONNECTED
+                    || App.connection_status == App.CONNECTION_STATE_CONNECTED_2) {
+                    countDownTimer!!.cancel()
+
+                    val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_CONNECT_VPN
+                    context.sendBroadcast(widgetIntent)
+                }
+                else if (App.connection_status == App.CONNECTION_STATE_DISCONNECTED) {
+                    countDownTimer!!.cancel()
+
+                    val widgetIntent = Intent(context, SimpleAppWidget::class.java)
+                    widgetIntent.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                    context.sendBroadcast(widgetIntent)
+                }
+            }
+
+            override fun onFinish() {
+                if (App.connection_status == App.CONNECTION_STATE_CONNECTING) {
+                    UIHelper.showToast(R.string.server_not_responding)
+                    stopVpn()
+                }
+            }
+        }
+    }
+
+    fun isVPNConnected(): Boolean {
+        try {
+            val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+            val networks = cm.allNetworks
+            for (network in networks) {
+                val caps = cm.getNetworkCapabilities(network)
+
+                if (caps!!.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) return true
+            }
+            return false
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+        return false
+    }
+
+    fun initUI() {
+        thread = object : Thread() {
+            override fun run() {
+                try {
+                    while (!thread!!.isInterrupted) {
+                        sleep(500)
+                        context.let {
+                            it.runOnUiThread {
+                                // set country flag
+                                if (App.abortConnection) {
+                                    App.abortConnection = false
+                                    if (App.connection_status != App.CONNECTION_STATE_CONNECTED) {
+                                        App.CountDown = 1
+                                    }
+                                    if (App.connection_status == App.CONNECTION_STATE_CONNECTED || App.connection_status == App.CONNECTION_STATE_CONNECTED_2) {
+                                        try {
+                                            stopVpn()
+//                                        vpnWireGuard(false)
+                                        } catch (e: Exception) {
+                                        }
+                                    }
+//                                else if (App.connection_status == App.CONNECTION_STATE_UP_WG) {
+//                                    try {
+//                                        Log.d("CONNECTION_STATE_UP_WG", App.CONNECTION_STATE_UP_WG.toString())
+//                                        vpnWireGuard(false)
+//                                    } catch (e: Exception) {
+//                                    }
+//                                }
+                                }
+
+
+                                vpnConnectionCallBacks.let {
+
+//                                Log.d("vpn connecting thread", App.connection_status.toString())
+
+
+                                    if (App.connection_status == App.CONNECTION_STATE_DISCONNECTED) { // disconnected
+                                        it.onVpnDisconnected()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+
+//                                    tunnelStatus = backend?.getState(tunnel)!!     // not using
+//                                    vpnWireGuard(false)                                // not using
+                                    }
+
+                                    else if (App.connection_status == App.CONNECTION_STATE_CONNECTING) { // connecting
+
+                                        it.onVpnConnecting()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+                                    }
+
+                                    else if (App.connection_status == App.CONNECTION_STATE_CONNECTED) { // connected
+
+//                                        Log.d("onVpn test Connected", "onVpnConnected... Thread")
+
+//                                    tunnelStatus = Tunnel.State.UP                // not using
+
+//                                    tunnelStatus = backend?.getState(tunnel)!!    // not using
+                                        it.onVpnConnected()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+                                    }
+
+                                    else if (App.connection_status == App.CONNECTION_STATE_CONNECTED_2) { // connected
+//                                    tunnelStatus = backend?.getState(tunnel)!!  // not using
+
+                                        it.onVpnConnected()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+//                                    tunnelStatus = Tunnel.State.UP             // not using
+                                    }
+                                    else if (App.connection_status == App.CONNECTION_STATE_UP_WG) {
+                                        App.tunnelStatus = Tunnel.State.UP  // HomeFragment.tunnelStatus
+                                        it.onVpnConnected()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+                                    }
+                                    else if (App.connection_status == App.CONNECTION_STATE_DOWN_WG) {
+//                                      tunnelStatus = Tunnel.State.DOWN           // not using
+                                        if (!StaticMethods.isTV(context)){
+                                            vpnWireGuard(false)               // using
+                                        }
+                                        it.onVpnDisconnected()
+                                        MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+                                    }
+                                }
+                            }
+                        }
+
+                    }
+                } catch (e: InterruptedException) {
+                    e.printStackTrace()
+                }
+            }
+        }
+        thread?.start()
+    }
+
+    fun onStopCallBack() {
+        VpnStatus.removeStateListener(this)
+    }
+
+    fun onResumeCallBack() {
+
+        try {
+            Log.d("test_openvpn", "mConnection = $mConnection")
+            VpnStatus.addStateListener(this)
+            val intent = Intent(context, OpenVPNService::class.java)
+            intent.action = OpenVPNService.START_SERVICE
+            context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+
+//        //setting receiver to listen ikev2 protocol connection states
+
+//        App.createIKEV2Listener()
+
+        /* Currently Commenting ... */
+//        try {
+//            LocalBroadcastManager.getInstance(context)
+//                .unregisterReceiver(WireGuardService.ikevConnectionStatesReceiver)
+//
+//        } catch (e: Exception) {
+//            e.printStackTrace()
+//        }
+
+        try {
+            ikevConnectionStatesReceiver = IkevConnectionStatesReceiver()
+            val filter = IntentFilter()
+            filter.addAction(CharonVpnService.ACTION_VPN_CONNECTED)
+            filter.addAction(CharonVpnService.ACTION_VPN_DISCONNECTED)
+            filter.addAction(CharonVpnService.ACTION_VPN_CONNECTING)
+            filter.addAction(CharonVpnService.ACTION_VPN_SERVER_NOT_RESPONDING)
+            LocalBroadcastManager.getInstance(context)
+                .registerReceiver(ikevConnectionStatesReceiver, filter)
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    fun onPauseCallBack() {
+        context.unbindService(mConnection)
+
+//        removing receiver to listen ikev2 protocol connection states
+
+        // Commenting Below Just Now ... !!!
+
+        try {
+            LocalBroadcastManager.getInstance(context)
+                .unregisterReceiver(ikevConnectionStatesReceiver)
+
+        } catch (e: Exception) {
+            e.printStackTrace()
+        }
+    }
+
+    override fun updateState(
+        state: String?, logmessage: String?, localizedResId: Int, level: ConnectionStatus?
+    ) {
+        if (level == ConnectionStatus.LEVEL_NOTCONNECTED) {
+            Log.d("vpnConnectionCall ip", "LEVEL_NOTCONNECTED")
+
+            vpnConnectionCallBacks.onGetIp()
+        }
+    }
+
+    override fun setConnectedVPN(uuid: String?) {
+    }
+
+    inner class IkevConnectionStatesReceiver : BroadcastReceiver() {
+        override fun onReceive(context: Context?, intent: Intent?) {
+            if (intent != null && intent.action != null) {
+                val action = intent.action
+                when (action) {
+                    CharonVpnService.ACTION_VPN_CONNECTED -> {
+                        Log.d("vpnConnectionCall ip", "ACTION_VPN_CONNECTED")
+                        App.connection_status = App.CONNECTION_STATE_CONNECTED
+                        vpnConnectionCallBacks.onVpnConnected()
+                        MainActivity.vpnConnectionCallBacks?.onVpnConnected()
+                        val widgetIntent1 = Intent(context, SimpleAppWidget::class.java)
+                        widgetIntent1.action = SimpleAppWidget.ACTION_CONNECT_VPN
+                        context?.sendBroadcast(widgetIntent1)
+                    }
+                    CharonVpnService.ACTION_VPN_DISCONNECTED -> {
+                        Log.d("vpnConnectionCall ip", "ACTION_VPN_DISCONNECTED")
+                        App.connection_status = App.CONNECTION_STATE_DISCONNECTED
+                        vpnConnectionCallBacks.onVpnDisconnected()
+                        MainActivity.vpnConnectionCallBacks?.onVpnDisconnected()
+                        val widgetIntent1 = Intent(context, SimpleAppWidget::class.java)
+                        widgetIntent1.action = SimpleAppWidget.ACTION_DISCONNECT_VPN
+                        context?.sendBroadcast(widgetIntent1)
+                        vpnConnectionCallBacks.onGetIp()
+                    }
+                    CharonVpnService.ACTION_VPN_CONNECTING -> {
+                        Log.d("vpnConnectionCall ip", "ACTION_VPN_CONNECTING")
+                        App.connection_status = App.CONNECTION_STATE_CONNECTING
+                        vpnConnectionCallBacks.onVpnConnecting()
+                        MainActivity.vpnConnectionCallBacks?.onVpnConnecting()
+                        val widgetIntent1 = Intent(context, SimpleAppWidget::class.java)
+                        widgetIntent1.action = SimpleAppWidget.ACTION_CONNECTING_VPN
+                        context?.sendBroadcast(widgetIntent1)
+                    }
+                    CharonVpnService.ACTION_VPN_SERVER_NOT_RESPONDING -> {
+                        Log.d("vpnConnectionCall ip", "ACTION_VPN_SERVER_NOT_RESPONDING")
+                        App.connection_status = App.CONNECTION_STATE_SERVER_NOT_RESPONDING
+                        vpnConnectionCallBacks.onServerNotResponding()
+                        MainActivity.vpnConnectionCallBacks?.onServerNotResponding()
+                    }
+                }
+            }
+        }
+    }
+
+    private fun getJsonFileDetails(): InputStream? {
+        var conf: InputStream? = null
+        try {
+            conf = if (basePreferenceHelper.getProtocol().title.equals(AppEnum.TCP_PROTOCOL.key)) {
+                context.assets.open("fileDetails/tcp.ovpn")
+            } else {
+                context.assets.open("fileDetails/udp.ovpn")
+            }
+
+            Log.d("test_openvpn", "conf = $conf")
+
+            return conf
+        } catch (e: java.lang.Exception) {
+            e.printStackTrace()
+        }
+        return null
+    }
+
+}

+ 4 - 3
app/src/main/res/layout-land/activity_home_tv.xml

@@ -77,7 +77,7 @@
                     app:cardCornerRadius="12.5dp">
 
                     <ImageView
-                        android:id="@+id/iv_country"
+                        android:id="@+id/iv_countryImg"
                         android:layout_width="wrap_content"
                         android:layout_height="wrap_content"
                         android:scaleType="centerCrop" />
@@ -258,7 +258,7 @@
                     app:cardCornerRadius="15dp">
 
                     <ImageView
-                        android:id="@+id/ivCountry"
+                        android:id="@+id/ivCountryServer"
                         android:layout_width="match_parent"
                         android:layout_height="match_parent"
                         android:elevation="0dp"
@@ -271,6 +271,7 @@
                     android:layout_height="wrap_content"
                     android:layout_marginStart="8dp"
                     android:layout_weight="1"
+                    android:maxLines="2"
                     android:fontFamily="@font/outfit_regular"
                     android:text="Select Server"
                     android:textColor="@color/white"
@@ -334,7 +335,7 @@
                 app:layout_constraintTop_toTopOf="parent"
                 app:layout_constraintVertical_bias="1.0" />
 
-            <FrameLayout
+            <androidx.fragment.app.FragmentContainerView
                 android:id="@+id/server_container"
                 android:layout_width="0dp"
                 android:layout_height="0dp"

+ 3 - 2
app/src/main/res/layout-land/item_server.xml

@@ -51,11 +51,12 @@
                 android:layout_width="match_parent"
                 android:layout_height="wrap_content"
                 android:layout_gravity="center"
-                android:layout_marginStart="10dp"
+                android:layout_marginStart="0dp"
                 android:layout_marginTop="10dp"
-                android:layout_marginEnd="@dimen/x10dp"
+                android:layout_marginEnd="0dp"
                 android:fontFamily="@font/outfit_regular"
                 android:gravity="center"
+                android:maxLines="2"
                 android:text="New York times checking"
                 android:textColor="#ffffff"
                 android:textSize="12dp" />

+ 1 - 1
app/src/main/res/layout/activity_home_tv.xml

@@ -292,7 +292,7 @@
                 app:cardCornerRadius="25dp">
 
                 <ImageView
-                    android:id="@+id/ivCountry"
+                    android:id="@+id/ivCountryServer"
                     android:layout_width="50dp"
                     android:layout_height="50dp"
                     android:elevation="0dp"

+ 1 - 0
app/src/main/res/layout/activity_main.xml

@@ -4,6 +4,7 @@
     <RelativeLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
+        android:background="@color/light_blue_2"
         android:fitsSystemWindows="false">
 
         <RelativeLayout

+ 4 - 1
app/src/main/res/values/themes.xml

@@ -11,7 +11,10 @@
         <item name="android:colorBackgroundCacheHint">@null</item>
         <!--        <item name="android:windowAnimationStyle">@android:style/Animation</item>-->
         <item name="android:windowAnimationStyle">@null</item>
-        <item name="android:windowBackground">@android:color/transparent</item>
+
+        <item name="android:windowDisablePreview">true</item>
+        <item name="android:windowBackground">@color/light_blue</item>
+<!--        <item name="android:windowBackground">@android:color/transparent</item>-->
         <item name="android:windowIsFloating">true</item>
         <item name="android:windowIsTranslucent">true</item>
         <item name="android:windowNoTitle">true</item>