- Create Kotlin file, e.g. named
Utils
; -
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 withoutContext
parameter:fun Activity.checkConnectivity(): Boolean { val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetwork =cm.activeNetworkInfo return activeNetwork != null && activeNetwork.isConnectedOrConnecting }
-
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?