owenclave / app/src/main/java/io/nekohasekai/sagernet/bg/ProxyService.kt

github - dev - back to tree - upstream
/****************************************************************************** * * * Copyright (C) 2021 by nekohasekai * * Copyright (C) 2021 by Max Lv * * Copyright (C) 2021 by Mygod Studio * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see . * * * ******************************************************************************/ package io.nekohasekai.sagernet.bg import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.net.Network import android.os.PowerManager import io.nekohasekai.sagernet.SagerNet import io.nekohasekai.sagernet.utils.DefaultNetworkListener import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class ProxyService : Service(), BaseService.Interface, LocalResolver { override val data = BaseService.Data(this) override val tag: String get() = "SagerNetProxyService" override fun createNotification(profileName: String): ServiceNotification = ServiceNotification(this, profileName, "service-proxy", true) override var wakeLock: PowerManager.WakeLock? = null @Volatile override var underlyingNetwork: Network? = null private var networkListenerIsRunning = false override suspend fun preInit() { networkListenerIsRunning = true DefaultNetworkListener.start(this) { if (networkListenerIsRunning) { SagerNet.reloadNetwork(it) underlyingNetwork = it } } } override suspend fun startProcesses() { data.proxy!!.v2rayPoint.withLocalResolver(this) super.startProcesses() } @Suppress("EXPERIMENTAL_API_USAGE") override fun killProcesses() { data.proxy?.v2rayPoint?.withLocalResolver(null) super.killProcesses() networkListenerIsRunning = false GlobalScope.launch(Dispatchers.Default) { DefaultNetworkListener.stop(this) } } @SuppressLint("WakelockTimeout") override fun acquireWakeLock() { wakeLock = SagerNet.power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "sagernet:proxy") .apply { acquire() } } override fun onBind(intent: Intent) = super.onBind(intent) override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = super.onStartCommand(intent, flags, startId) override fun onDestroy() { super.onDestroy() data.binder.close() } }