web服务通知栏支持多个地址

This commit is contained in:
Antecer 2024-04-06 23:09:54 +08:00
parent 328f01d0bf
commit f15cbe2d73
2 changed files with 16 additions and 17 deletions

View File

@ -76,13 +76,14 @@ class WebService : BaseService() {
upTile(true)
networkChangedListener.register()
networkChangedListener.onNetworkChanged = {
val address = NetworkUtils.getLocalIPAddress()
if (address == null) {
hostAddress = getString(R.string.network_connection_unavailable)
notificationContent = hostAddress
val addressList = NetworkUtils.getLocalIPAddress()
if (addressList.any()) {
val hostList = addressList.map { address -> getString(R.string.http_ip, address.hostAddress, getPort()) }
hostAddress = hostList.first()
notificationContent = hostList.joinToString(separator = "\n")
startForegroundNotification()
} else {
hostAddress = getString(R.string.http_ip, address.hostAddress, getPort())
hostAddress = getString(R.string.network_connection_unavailable)
notificationContent = hostAddress
startForegroundNotification()
}
@ -130,18 +131,19 @@ class WebService : BaseService() {
if (webSocketServer?.isAlive == true) {
webSocketServer?.stop()
}
val address = NetworkUtils.getLocalIPAddress()
if (address != null) {
val addressList = NetworkUtils.getLocalIPAddress()
if (addressList.any()) {
val port = getPort()
httpServer = HttpServer(port)
webSocketServer = WebSocketServer(port + 1)
try {
httpServer?.start()
webSocketServer?.start(1000 * 30) // 通信超时设置
hostAddress = getString(R.string.http_ip, address.hostAddress, port)
val hostList = addressList.map { address -> getString(R.string.http_ip, address.hostAddress, getPort()) }
hostAddress = hostList.first()
notificationContent = hostList.joinToString(separator = "\n")
isRun = true
postEvent(EventBus.WEB_SERVICE, hostAddress)
notificationContent = hostAddress
startForegroundNotification()
} catch (e: IOException) {
toastOnUi(e.localizedMessage ?: "")

View File

@ -188,16 +188,16 @@ object NetworkUtils {
/**
* Get local Ip address.
*/
fun getLocalIPAddress(): InetAddress? {
fun getLocalIPAddress(): List<InetAddress> {
val enumeration: Enumeration<NetworkInterface>
try {
enumeration = NetworkInterface.getNetworkInterfaces()
} catch (e: SocketException) {
e.printOnDebug()
return null
return mutableListOf()
}
var fallbackAddress: InetAddress? = null
var fallbackAddress: MutableList<InetAddress> = mutableListOf()
while (enumeration.hasMoreElements()) {
val nif = enumeration.nextElement()
@ -205,11 +205,8 @@ object NetworkUtils {
while (addresses.hasMoreElements()) {
val address = addresses.nextElement()
if (!address.isLoopbackAddress && isIPv4Address(address.hostAddress)) {
if (nif.name?.startsWith("wl") == true) {
return address
}
if (fallbackAddress == null) {
fallbackAddress = address
if (nif.name?.startsWith("wlan") == true) {
fallbackAddress.add(address)
}
}
}