I use ConnectivityManager
to listen internet connection change inside app like this.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
ConnectionStateMonitor().enable(this)
}
class ConnectionStateMonitor : NetworkCallback() {
private val networkRequest: NetworkRequest = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI).build()
fun enable(context: Context) {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager.registerNetworkCallback(networkRequest, this)
}
override fun onAvailable(network: Network) {
Log.i(TAG, "onAvailable ")
}
override fun onLost(network: Network?) {
super.onLost(network)
Log.i(TAG, "onLost ")
}
}
}
It working good except some problem
-
If we connect to internet by both wifi and mobile data, when we turn off wifi then sometime onLost fired -> onAvailable fired (CORRECT) and sometime only onLost fired (WRONG)
-
Also, there is another problem: If we don't have internet connection -> open app -> onLost() not fired. However, if we have internet connection -> open app -> onAvailable fired
Any help, suggestion, workaround or another approach to detect internet connection change would be great appreciate.
Tested on Xioami A2 (Android 9), OnePlus (Android 9)
DEMO project
https://github.com/PhanVanLinh/AndroidNetworkChangeReceiver
from Android ConnectivityManager onAvailable sometime not returned
No comments:
Post a Comment