Huge refactor for better maintainability

This commit is contained in:
Mygod
2018-06-01 20:21:05 +08:00
parent a5bec59bbe
commit 8aa7d6d8c7
35 changed files with 1072 additions and 824 deletions

View File

@@ -12,23 +12,26 @@ import android.support.v4.app.Fragment
import kotlin.reflect.KClass
/**
* host also needs to be Context/Fragment and LifecycleOwner.
* owner also needs to be Context/Fragment.
*/
class ServiceForegroundConnector(private val host: ServiceConnection, private val classes: List<KClass<out Service>>) :
LifecycleObserver {
class ServiceForegroundConnector(private val owner: LifecycleOwner, private val connection: ServiceConnection,
private val clazz: KClass<out Service>) : LifecycleObserver {
init {
(host as LifecycleOwner).lifecycle.addObserver(this)
owner.lifecycle.addObserver(this)
}
constructor(host: ServiceConnection, vararg classes: KClass<out Service>) : this(host, classes.toList())
private val context get() = if (host is Context) host else (host as Fragment).requireContext()
private val context get() = when (owner) {
is Context -> owner
is Fragment -> owner.requireContext()
else -> throw UnsupportedOperationException("Unsupported owner")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
val context = context
for (clazz in classes) context.bindService(Intent(context, clazz.java), host, Context.BIND_AUTO_CREATE)
context.bindService(Intent(context, clazz.java), connection, Context.BIND_AUTO_CREATE)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop() = context.stopAndUnbind(host)
fun onStop() = context.stopAndUnbind(connection)
}

View File

@@ -4,6 +4,7 @@ import android.content.*
import android.databinding.BindingAdapter
import android.support.annotation.DrawableRes
import android.util.Log
import android.view.View
import android.widget.ImageView
import be.mygod.vpnhotspot.App.Companion.app
import be.mygod.vpnhotspot.BuildConfig
@@ -28,6 +29,11 @@ fun intentFilter(vararg actions: String): IntentFilter {
@BindingAdapter("android:src")
fun setImageResource(imageView: ImageView, @DrawableRes resource: Int) = imageView.setImageResource(resource)
@BindingAdapter("android:visibility")
fun setVisibility(view: View, value: Boolean) {
view.visibility = if (value) View.VISIBLE else View.GONE
}
fun NetworkInterface.formatAddresses() =
(interfaceAddresses.asSequence()
.map { "${it.address.hostAddress}/${it.networkPrefixLength}" }