Skip to content Skip to sidebar Skip to footer

How To Call This Function From Other Activities?

i need help in this kotlin code pls ... i have checkConnctivvity() function and it's working perfectly ... fun checkConnectivity(){ val cm=getSystemService(Context.CONNECTIVI

Solution 1:

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

    funcheckConnectivity(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()
    

Post a Comment for "How To Call This Function From Other Activities?"