Skip to content

Commit

Permalink
Implement a check to start V2Ray if the network connected (#3439)
Browse files Browse the repository at this point in the history
* Implement isNetworkConnected functionality

* Implement a check to start V2Ray if the network connected
  • Loading branch information
Amir-yazdanmanesh authored Aug 10, 2024
1 parent 9d109e7 commit 4570fdb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
18 changes: 18 additions & 0 deletions V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.v2ray.ang.extension

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Build
import android.widget.Toast
import com.v2ray.ang.AngApplication
Expand Down Expand Up @@ -55,3 +57,19 @@ val URI.idnHost: String
get() = host?.replace("[", "")?.replace("]", "") ?: ""

fun String.removeWhiteSpace(): String = replace("\\s+".toRegex(), "")

val Context.isNetworkConnected: Boolean
get() {
val manager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
manager.getNetworkCapabilities(manager.activeNetwork)?.let {
it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) ||
it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
it.hasTransport(NetworkCapabilities.TRANSPORT_BLUETOOTH) ||
it.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) ||
it.hasTransport(NetworkCapabilities.TRANSPORT_VPN)
} ?: false
else
@Suppress("DEPRECATION")
manager.activeNetworkInfo?.isConnectedOrConnecting == true
}
11 changes: 8 additions & 3 deletions V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import com.v2ray.ang.R
import com.v2ray.ang.databinding.ActivityMainBinding
import com.v2ray.ang.databinding.LayoutProgressBinding
import com.v2ray.ang.dto.EConfigType
import com.v2ray.ang.extension.isNetworkConnected
import com.v2ray.ang.extension.toast
import com.v2ray.ang.helper.SimpleItemTouchHelperCallback
import com.v2ray.ang.service.V2RayServiceManager
Expand Down Expand Up @@ -200,10 +201,14 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
}

fun startV2Ray() {
if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) {
return
if (isNetworkConnected) {
if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) {
return
}
V2RayServiceManager.startV2Ray(this)
} else {
ToastCompat.makeText(this, getString(R.string.connection_test_fail), Toast.LENGTH_LONG).show()
}
V2RayServiceManager.startV2Ray(this)
}

fun restartV2Ray() {
Expand Down

0 comments on commit 4570fdb

Please sign in to comment.