0

`I want my Android application to check for an internet connection on the first launch and prevent any further execution (such as API requests) if the internet is not available. If the internet is available, the application should continue as expected.

I am using the Network class to check for internet availability and have implemented the following logic`

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    installSplashScreen()
    setContentView(R.layout.activity_main)
    checkPermissionsAndInternet()
}

private fun checkPermissionsAndInternet() {
    permissionsHelper.check {
        arePermissionsGranted = true
        if (!isInternetAvailable()) {
            showNoInternetDialog()
        } else {
            startAppAfterPermissionsGranted()
        }
    }
}

private fun isInternetAvailable(): Boolean {
    val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val network = connectivityManager.activeNetwork ?: return false
    val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
    return activeNetwork.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
}

private fun startAppAfterPermissionsGranted() {
    arePermissionsGranted = true
    (application as App).appComponent.inject(this)
    mainViewModel.setMainActivityInstance(this)
}````




`How can I ensure that the application does not proceed if there is no internet connection on the first launch?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.