Skip to content

Commit

Permalink
fix client
Browse files Browse the repository at this point in the history
  • Loading branch information
rikaaa0928 committed Oct 17, 2024
1 parent 2953fc8 commit 221aae6
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 35 deletions.
87 changes: 58 additions & 29 deletions app/src/main/java/moe/rikaaa0928/uot/UogClient.kt
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
package moe.rikaaa0928.uot

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.util.Log
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import uniffi.uog.startClient
Expand All @@ -15,22 +12,26 @@ import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference

class UogClient(val lPort: Int, val endpoint: String, val password: String) : BroadcastReceiver() {
class UogClient(
val lPort: Int,
val endpoint: String,
val password: String,
val connectivityManager: ConnectivityManager
) :
ConnectivityManager.NetworkCallback() {
// private var service: UdpServiceGrpcKt.UdpServiceCoroutineStub? = null

private val stop = AtomicBoolean(true)
private val waitNet: AtomicReference<CountDownLatch> = AtomicReference(null)
private val waitNet: AtomicReference<CountDownLatch> = AtomicReference(CountDownLatch(1))


@OptIn(DelicateCoroutinesApi::class)
fun start() {
stop.set(false)
GlobalScope.launch {
while (!stop.get()) {
try {
val res = startClient("127.0.0.1:$lPort", endpoint, password)
Log.e("UogClient", "startClient exit $res")
} catch (e: Exception) {
} catch (e: Throwable) {
Log.e("UogClient", "all", e)
} finally {
val l = waitNet.get()
Expand All @@ -49,28 +50,56 @@ class UogClient(val lPort: Int, val endpoint: String, val password: String) : Br
stop.set(true)
}

override fun onReceive(context: Context, intent: Intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
var isWifiConnected = false
var isMobileDataConnected = false

// override fun onReceive(context: Context, intent: Intent) {
// if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) {
// try {
// val connectivityManager =
// context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
// var isWifiConnected = false
// var isMobileDataConnected = false
//
//
// val network = connectivityManager.activeNetwork
// val capabilities = connectivityManager.getNetworkCapabilities(network)
//
// if (capabilities != null) {
// isWifiConnected = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
// isMobileDataConnected =
// capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
// }
// if (!isWifiConnected && !isMobileDataConnected) {
// waitNet.compareAndSet(null, CountDownLatch(1))
// } else {
// val l = waitNet.getAndSet(null)
// l?.countDown()
// }
// } catch (e: Exception) {
// Log.e("UogClient", "onReceive", e)
// }
// }
// }

val network = connectivityManager.activeNetwork
val capabilities = connectivityManager.getNetworkCapabilities(network)
override fun onAvailable(network: Network) {
Log.d("NetworkCallback", "Network onAvailable: $network")
// 网络可用时调用
val l = waitNet.getAndSet(null)
l?.countDown()
}

if (capabilities != null) {
isWifiConnected = capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
isMobileDataConnected =
capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
}
if (!isWifiConnected && !isMobileDataConnected) {
waitNet.compareAndSet(null, CountDownLatch(1))
} else {
val l = waitNet.getAndSet(null)
l?.countDown()
}
override fun onLost(network: Network) {
// 网络丢失时调用
Log.d("NetworkCallback", "Network onLost: $network")
val activeNetwork = connectivityManager.activeNetwork
if (activeNetwork == null) {
Log.d("NetworkCallback", "设备当前没有活跃的网络连接")
waitNet.compareAndSet(null, CountDownLatch(1))
} else {
Log.d("NetworkCallback", "设备仍有其他活跃的网络连接")
}
}

override fun onCapabilitiesChanged(network: Network, networkCapabilities: NetworkCapabilities) {
// 网络能力变化时调用,可以检查具体的网络类型
Log.d("NetworkCallback", "Network onCapabilitiesChanged: $network $networkCapabilities")
}
}
26 changes: 20 additions & 6 deletions app/src/main/java/moe/rikaaa0928/uot/UotGrpc.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ServiceInfo
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.os.IBinder
import android.util.Log
Expand All @@ -20,18 +22,26 @@ import androidx.core.app.ServiceCompat
class UotGrpc : Service() {
var client: UogClient? = null
val channelId = "UogChannel"
var connectivityManager: ConnectivityManager? = null
override fun onCreate() {
super.onCreate()
connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
startForegroundService()
// TODO: Initialize gRPC stream here
val sharedPreferences = getSharedPreferences("AppConfig", MODE_PRIVATE)
client = UogClient(
sharedPreferences.getString("ListenPort", "0")!!.toInt(),
sharedPreferences.getString("GrpcEndpoint", "")!!,
sharedPreferences.getString("Password", "")!!
sharedPreferences.getString("Password", "")!!,
connectivityManager!!
)
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(client, filter)
// val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
// registerReceiver(client, filter)
val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()

connectivityManager!!.registerNetworkCallback(networkRequest, client!!)
}

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Expand All @@ -44,20 +54,24 @@ class UotGrpc : Service() {
super.onDestroy()
// TODO: Clean up gRPC stream here
client!!.stop()
unregisterReceiver(client)
connectivityManager!!.unregisterNetworkCallback(client!!)
// unregisterReceiver(client)
}

override fun onBind(intent: Intent?): IBinder? {
return null
}

private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "uog", NotificationManager.IMPORTANCE_DEFAULT);
val notificationManager:NotificationManager =
val channel =
NotificationChannel(channelId, "uog", NotificationManager.IMPORTANCE_DEFAULT);
val notificationManager: NotificationManager =
getSystemService(NOTIFICATION_SERVICE) as NotificationManager;
notificationManager.createNotificationChannel(channel);
}
}

private fun startForegroundService() {
try {
createNotificationChannel();
Expand Down

0 comments on commit 221aae6

Please sign in to comment.