- Create Kotlin file, e.g. named
Utils; -
Move function to that file, and add
Contextparameter: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
Activityyou can create extension function withoutContextparameter: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
Activityjust use code:checkConnectivity(this@YourActivity)If you created extension function, just call it in
Activitywithout passing any parameters:checkConnectivity()
3
solved How to call this function from other activities?