Stop using deprecated launchWhenX

This commit is contained in:
Mygod
2023-03-02 22:00:18 -05:00
parent b123aa8b43
commit 94fd4cc45b
7 changed files with 65 additions and 37 deletions

View File

@@ -105,7 +105,7 @@ class EBegFragment : AppCompatDialogFragment() {
billingClient.startConnection(EBegFragment) billingClient.startConnection(EBegFragment)
} }
private fun onBillingConnected() = viewLifecycleOwner.lifecycleScope.launchWhenStarted { private fun onBillingConnected() = viewLifecycleOwner.lifecycleScope.launch {
billingClient.queryProductDetails(QueryProductDetailsParams.newBuilder().apply { billingClient.queryProductDetails(QueryProductDetailsParams.newBuilder().apply {
setProductList(listOf( setProductList(listOf(
"donate001", "donate002", "donate005", "donate010", "donate020", "donate050", "donate001", "donate002", "donate005", "donate010", "donate020", "donate050",

View File

@@ -49,7 +49,7 @@ class SettingsPreferenceFragment : PreferenceFragmentCompat() {
findPreference<TwoStatePreference>("system.enableTetherOffload")!!.apply { findPreference<TwoStatePreference>("system.enableTetherOffload")!!.apply {
isChecked = TetherOffloadManager.enabled isChecked = TetherOffloadManager.enabled
setOnPreferenceChangeListener { _, newValue -> setOnPreferenceChangeListener { _, newValue ->
if (TetherOffloadManager.enabled != newValue) viewLifecycleOwner.lifecycleScope.launchWhenCreated { if (TetherOffloadManager.enabled != newValue) viewLifecycleOwner.lifecycleScope.launch {
isEnabled = false isEnabled = false
try { try {
TetherOffloadManager.setEnabled(newValue as Boolean) TetherOffloadManager.setEnabled(newValue as Boolean)

View File

@@ -21,6 +21,7 @@ import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels import androidx.fragment.app.activityViewModels
import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.findViewTreeLifecycleOwner
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.withStarted
import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.ListAdapter
@@ -158,14 +159,16 @@ class ClientsFragment : Fragment() {
true true
} }
R.id.stats -> { R.id.stats -> {
binding.client?.let { client -> val client = binding.client
viewLifecycleOwner.lifecycleScope.launchWhenCreated { val title = client?.title?.value ?: return false
withContext(Dispatchers.Unconfined) { viewLifecycleOwner.lifecycleScope.launch {
StatsDialogFragment().apply { val stats = withContext(Dispatchers.Unconfined) {
arg(StatsArg(client.title.value ?: return@withContext, AppDatabase.instance.trafficRecordDao.queryStats(client.mac)
AppDatabase.instance.trafficRecordDao.queryStats(client.mac)))
}.showAllowingStateLoss(parentFragmentManager)
} }
withStarted {
StatsDialogFragment().apply {
arg(StatsArg(title, stats))
}.showAllowingStateLoss(parentFragmentManager)
} }
} }
true true
@@ -238,14 +241,19 @@ class ClientsFragment : Fragment() {
override fun onStart() { override fun onStart() {
// icon might be changed due to TetherType changes // icon might be changed due to TetherType changes
if (Build.VERSION.SDK_INT >= 30) TetherType.listener[this] = { if (Build.VERSION.SDK_INT >= 30) TetherType.listener[this] = {
lifecycleScope.launchWhenStarted { adapter.notifyItemRangeChanged(0, adapter.size.await()) } lifecycleScope.launch {
val size = adapter.size.await()
withStarted { adapter.notifyItemRangeChanged(0, size) }
}
} }
super.onStart() super.onStart()
// we just put these two thing together as this is the only place we need to use this event for now // we just put these two thing together as this is the only place we need to use this event for now
TrafficRecorder.foregroundListeners[this] = { newRecords, oldRecords -> TrafficRecorder.foregroundListeners[this] = { newRecords, oldRecords ->
lifecycleScope.launchWhenStarted { adapter.updateTraffic(newRecords, oldRecords) } lifecycleScope.launch {
withStarted { adapter.updateTraffic(newRecords, oldRecords) }
} }
lifecycleScope.launchWhenStarted { }
lifecycleScope.launch {
withContext(Dispatchers.Default) { withContext(Dispatchers.Default) {
TrafficRecorder.rescheduleUpdate() // next schedule time might be 1 min, force reschedule to <= 1s TrafficRecorder.rescheduleUpdate() // next schedule time might be 1 min, force reschedule to <= 1s
} }

View File

@@ -22,6 +22,7 @@ import androidx.databinding.Bindable
import androidx.fragment.app.viewModels import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.withStarted
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import be.mygod.vpnhotspot.AlertDialogFragment import be.mygod.vpnhotspot.AlertDialogFragment
import be.mygod.vpnhotspot.BR import be.mygod.vpnhotspot.BR
@@ -156,8 +157,10 @@ class RepeaterManager(private val parent: TetheringFragment) : Manager(), Servic
fun configure() { fun configure() {
if (configuring) return if (configuring) return
configuring = true configuring = true
parent.viewLifecycleOwner.lifecycleScope.launchWhenCreated { val owner = parent.viewLifecycleOwner
getConfiguration()?.let { (config, readOnly) -> owner.lifecycleScope.launch {
val (config, readOnly) = getConfiguration() ?: return@launch
owner.withStarted {
WifiApDialogFragment().apply { WifiApDialogFragment().apply {
arg(WifiApDialogFragment.Arg(config, readOnly, true)) arg(WifiApDialogFragment.Arg(config, readOnly, true))
key(this@RepeaterManager.javaClass.name) key(this@RepeaterManager.javaClass.name)

View File

@@ -1,5 +1,3 @@
@file:Suppress("DEPRECATION")
package be.mygod.vpnhotspot.manage package be.mygod.vpnhotspot.manage
import android.annotation.TargetApi import android.annotation.TargetApi
@@ -18,6 +16,7 @@ import androidx.appcompat.widget.Toolbar
import androidx.core.content.getSystemService import androidx.core.content.getSystemService
import androidx.fragment.app.Fragment import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.withStarted
import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.ListAdapter
@@ -41,6 +40,8 @@ import be.mygod.vpnhotspot.widget.SmartSnackbar
import com.google.android.material.snackbar.Snackbar import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber import timber.log.Timber
import java.lang.reflect.InvocationTargetException import java.lang.reflect.InvocationTargetException
import java.net.NetworkInterface import java.net.NetworkInterface
@@ -84,10 +85,14 @@ class TetheringFragment : Fragment(), ServiceConnection, Toolbar.OnMenuItemClick
updateEnabledTypes() updateEnabledTypes()
val lastList = listDeferred.await() val lastList = listDeferred.await()
var first = lastList.indexOfFirst { it is InterfaceManager } var first = lastList.indexOfFirst { it is InterfaceManager }
if (first >= 0) notifyItemRangeChanged(first, lastList.indexOfLast { it is InterfaceManager } - first + 1) withStarted {
if (first >= 0) {
notifyItemRangeChanged(first, lastList.indexOfLast { it is InterfaceManager } - first + 1)
}
first = lastList.indexOfLast { it !is TetherManager } + 1 first = lastList.indexOfLast { it !is TetherManager } + 1
notifyItemRangeChanged(first, lastList.size - first) notifyItemRangeChanged(first, lastList.size - first)
} }
}
fun update() { fun update() {
val deferred = CompletableDeferred<List<Manager>>() val deferred = CompletableDeferred<List<Manager>>()
@@ -188,33 +193,34 @@ class TetheringFragment : Fragment(), ServiceConnection, Toolbar.OnMenuItemClick
} }
R.id.configuration_ap -> if (apConfigurationRunning) false else { R.id.configuration_ap -> if (apConfigurationRunning) false else {
apConfigurationRunning = true apConfigurationRunning = true
viewLifecycleOwner.lifecycleScope.launchWhenCreated { viewLifecycleOwner.lifecycleScope.launch {
try { val configuration = try {
if (Build.VERSION.SDK_INT < 30) { if (Build.VERSION.SDK_INT < 30) @Suppress("DEPRECATION") {
WifiApManager.configurationLegacy?.toCompat() ?: SoftApConfigurationCompat() WifiApManager.configurationLegacy?.toCompat() ?: SoftApConfigurationCompat()
} else WifiApManager.configuration.toCompat() } else WifiApManager.configuration.toCompat()
} catch (e: InvocationTargetException) { } catch (e: InvocationTargetException) {
if (e.targetException !is SecurityException) Timber.w(e) if (e.targetException !is SecurityException) Timber.w(e)
try { try {
if (Build.VERSION.SDK_INT < 30) { if (Build.VERSION.SDK_INT < 30) @Suppress("DEPRECATION") {
RootManager.use { it.execute(WifiApCommands.GetConfigurationLegacy()) }?.toCompat() RootManager.use { it.execute(WifiApCommands.GetConfigurationLegacy()) }?.toCompat()
?: SoftApConfigurationCompat() ?: SoftApConfigurationCompat()
} else RootManager.use { it.execute(WifiApCommands.GetConfiguration()) }.toCompat() } else RootManager.use { it.execute(WifiApCommands.GetConfiguration()) }.toCompat()
} catch (_: CancellationException) { } catch (_: CancellationException) {
null return@launch
} catch (eRoot: Exception) { } catch (eRoot: Exception) {
eRoot.addSuppressed(e) eRoot.addSuppressed(e)
if (Build.VERSION.SDK_INT >= 29 || eRoot.getRootCause() !is SecurityException) { if (Build.VERSION.SDK_INT >= 29 || eRoot.getRootCause() !is SecurityException) {
Timber.w(eRoot) Timber.w(eRoot)
} }
SmartSnackbar.make(eRoot).show() SmartSnackbar.make(eRoot).show()
null return@launch
} }
} catch (e: IllegalArgumentException) { } catch (e: IllegalArgumentException) {
Timber.w(e) Timber.w(e)
SmartSnackbar.make(e).show() SmartSnackbar.make(e).show()
null return@launch
}?.let { configuration -> }
withStarted {
WifiApDialogFragment().apply { WifiApDialogFragment().apply {
arg(WifiApDialogFragment.Arg(configuration)) arg(WifiApDialogFragment.Arg(configuration))
key() key()
@@ -230,7 +236,7 @@ class TetheringFragment : Fragment(), ServiceConnection, Toolbar.OnMenuItemClick
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
AlertDialogFragment.setResultListener<WifiApDialogFragment, WifiApDialogFragment.Arg>(this) { which, ret -> AlertDialogFragment.setResultListener<WifiApDialogFragment, WifiApDialogFragment.Arg>(this) { which, ret ->
if (which == DialogInterface.BUTTON_POSITIVE) viewLifecycleOwner.lifecycleScope.launchWhenCreated { if (which == DialogInterface.BUTTON_POSITIVE) GlobalScope.launch {
val configuration = ret!!.configuration val configuration = ret!!.configuration
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
if (Build.VERSION.SDK_INT < 30 && if (Build.VERSION.SDK_INT < 30 &&
@@ -241,12 +247,12 @@ class TetheringFragment : Fragment(), ServiceConnection, Toolbar.OnMenuItemClick
SmartSnackbar.make(e).show() SmartSnackbar.make(e).show()
} }
val success = try { val success = try {
if (Build.VERSION.SDK_INT < 30) { if (Build.VERSION.SDK_INT < 30) @Suppress("DEPRECATION") {
WifiApManager.setConfiguration(configuration.toWifiConfiguration()) WifiApManager.setConfiguration(configuration.toWifiConfiguration())
} else WifiApManager.setConfiguration(configuration.toPlatform()) } else WifiApManager.setConfiguration(configuration.toPlatform())
} catch (e: InvocationTargetException) { } catch (e: InvocationTargetException) {
try { try {
if (Build.VERSION.SDK_INT < 30) { if (Build.VERSION.SDK_INT < 30) @Suppress("DEPRECATION") {
val wc = configuration.toWifiConfiguration() val wc = configuration.toWifiConfiguration()
RootManager.use { it.execute(WifiApCommands.SetConfigurationLegacy(wc)) } RootManager.use { it.execute(WifiApCommands.SetConfigurationLegacy(wc)) }
} else { } else {
@@ -292,11 +298,17 @@ class TetheringFragment : Fragment(), ServiceConnection, Toolbar.OnMenuItemClick
override fun onServiceConnected(name: ComponentName?, service: IBinder?) { override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
binder = service as TetheringService.Binder binder = service as TetheringService.Binder
service.routingsChanged[this] = { lifecycleScope.launchWhenStarted { adapter.update() } } service.routingsChanged[this] = {
lifecycleScope.launch {
withStarted { adapter.update() }
}
}
requireContext().registerReceiver(receiver, IntentFilter(TetheringManager.ACTION_TETHER_STATE_CHANGED)) requireContext().registerReceiver(receiver, IntentFilter(TetheringManager.ACTION_TETHER_STATE_CHANGED))
if (Build.VERSION.SDK_INT >= 30) { if (Build.VERSION.SDK_INT >= 30) {
TetheringManager.registerTetheringEventCallback(null, adapter) TetheringManager.registerTetheringEventCallback(null, adapter)
TetherType.listener[this] = { lifecycleScope.launchWhenStarted { adapter.notifyTetherTypeChanged() } } TetherType.listener[this] = {
lifecycleScope.launch { adapter.notifyTetherTypeChanged() }
}
} }
} }

View File

@@ -10,12 +10,14 @@ import android.view.ViewGroup
import android.widget.ArrayAdapter import android.widget.ArrayAdapter
import androidx.core.os.bundleOf import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.withStarted
import androidx.preference.EditTextPreferenceDialogFragmentCompat import androidx.preference.EditTextPreferenceDialogFragmentCompat
import be.mygod.vpnhotspot.R import be.mygod.vpnhotspot.R
import be.mygod.vpnhotspot.util.Services import be.mygod.vpnhotspot.util.Services
import be.mygod.vpnhotspot.util.allInterfaceNames import be.mygod.vpnhotspot.util.allInterfaceNames
import be.mygod.vpnhotspot.util.globalNetworkRequestBuilder import be.mygod.vpnhotspot.util.globalNetworkRequestBuilder
import be.mygod.vpnhotspot.widget.AlwaysAutoCompleteEditText import be.mygod.vpnhotspot.widget.AlwaysAutoCompleteEditText
import kotlinx.coroutines.launch
class AutoCompleteNetworkPreferenceDialogFragment : EditTextPreferenceDialogFragmentCompat() { class AutoCompleteNetworkPreferenceDialogFragment : EditTextPreferenceDialogFragmentCompat() {
fun setArguments(key: String) { fun setArguments(key: String) {
@@ -33,12 +35,16 @@ class AutoCompleteNetworkPreferenceDialogFragment : EditTextPreferenceDialogFrag
private val callback = object : ConnectivityManager.NetworkCallback() { private val callback = object : ConnectivityManager.NetworkCallback() {
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) { override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
interfaceNames[network] = properties.allInterfaceNames interfaceNames[network] = properties.allInterfaceNames
lifecycleScope.launchWhenStarted { updateAdapter() } lifecycleScope.launch {
withStarted { updateAdapter() }
}
} }
override fun onLost(network: Network) { override fun onLost(network: Network) {
interfaceNames.remove(network) interfaceNames.remove(network)
lifecycleScope.launchWhenStarted { updateAdapter() } lifecycleScope.launch {
withStarted { updateAdapter() }
}
} }
} }

View File

@@ -8,7 +8,6 @@ import android.text.style.StyleSpan
import android.util.AttributeSet import android.util.AttributeSet
import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.preference.Preference import androidx.preference.Preference
import be.mygod.vpnhotspot.R import be.mygod.vpnhotspot.R
import be.mygod.vpnhotspot.net.monitor.FallbackUpstreamMonitor import be.mygod.vpnhotspot.net.monitor.FallbackUpstreamMonitor
@@ -67,7 +66,7 @@ class UpstreamsPreference(context: Context, attrs: AttributeSet) : Preference(co
FallbackUpstreamMonitor.unregisterCallback(fallback) FallbackUpstreamMonitor.unregisterCallback(fallback)
} }
private fun onUpdate() = (context as LifecycleOwner).lifecycleScope.launchWhenStarted { private fun onUpdate() {
summary = context.getText(R.string.settings_service_upstream_monitor_summary).format( summary = context.getText(R.string.settings_service_upstream_monitor_summary).format(
context.resources.configuration.locales[0], primary.charSequence, fallback.charSequence) context.resources.configuration.locales[0], primary.charSequence, fallback.charSequence)
} }