[Solved] How to call this function from other activities?


  1. Create Kotlin file, e.g. named Utils;
  2. Move function to that file, and add Context parameter:

    fun checkConnectivity(ctx: Context): Boolean {
        val cm = ctx.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork =cm.activeNetworkInfo
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting
    } 
    

    If you intend to use it only in Activity you can create extension function without Context parameter:

    fun Activity.checkConnectivity(): Boolean {
        val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val activeNetwork =cm.activeNetworkInfo
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting
    }
    
  3. Call that function from wherever you want. If you call it from Activity just use code:

    checkConnectivity(this@YourActivity)
    

    If you created extension function, just call it in Activity without passing any parameters:

    checkConnectivity()
    

3

solved How to call this function from other activities?