parent
0038b64fe4
commit
0abd0f73cd
@ -0,0 +1,63 @@
|
||||
package com.common.commonlib.utils
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.Activity
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.graphics.Bitmap
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.Network
|
||||
import android.net.NetworkRequest
|
||||
import android.provider.Settings
|
||||
import androidx.fragment.app.FragmentActivity
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleObserver
|
||||
import androidx.lifecycle.OnLifecycleEvent
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
object NetworkHelper {
|
||||
|
||||
/**
|
||||
* 网络状态监听
|
||||
*/
|
||||
inline fun observerNetworkState(activity: FragmentActivity, crossinline callback: (Boolean) -> Unit) {
|
||||
val manager = activity.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
val networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||
override fun onAvailable(network: Network) {
|
||||
super.onAvailable(network)
|
||||
if (activity.isAlive) {
|
||||
activity.runOnUiThread { callback(true) }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onLost(network: Network) {
|
||||
super.onLost(network)
|
||||
if (activity.isAlive) {
|
||||
activity.runOnUiThread { callback(false) }
|
||||
}
|
||||
}
|
||||
}
|
||||
manager.requestNetwork(NetworkRequest.Builder().build(), networkCallback)
|
||||
|
||||
activity.lifecycle.addObserver(object : LifecycleObserver {
|
||||
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
|
||||
fun onDestroy() {
|
||||
manager.unregisterNetworkCallback(networkCallback)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
fun isNetworkConnect(context: Context): Boolean {
|
||||
val cm = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
return cm.activeNetworkInfo?.isAvailable ?: false
|
||||
}
|
||||
|
||||
fun toNetworkSetting(context: Context) {
|
||||
val intent = Intent(Settings.ACTION_WIFI_SETTINGS)
|
||||
context.startActivity(intent)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue