Android Kotlin

10 Cool Android Context Kotlin Extension Functions

Prerequisites: If you don’t know what is kotlin extension functions I encouraged you to first read this article then continue.

Kotlin has this concept of extension function, which provides us to write the handy function without extending the existing class. As the title of this article describes, we’ll write some of the cool extension functions for Android Context class. Context is the most widely used class in Android development.

So, in this article, we’ll see some useful kotlin extension functions for Android Context class.

Table of Contents:

  1. Helper method to create the notification
  2. Extension Function to send local broadcast Async
  3. Extension Function to send local broadcast Sync
  4. Helper method to see if the particular service is running
  5. Launch chrome custom tabs extension function
  6. Enqueue the Worker (WorkManager) with kotlin extension function
  7. Helper variable’s to get system services
  8. Checking runtime permission with extension function
  9. Different helper methods to show a toast
  10. Get ContextCompat drawable and color helper method

show me the code.

1. Helper Method to create the notification

Displaying notifications on Android with Kotlin extension function is fairly easy. You just need to call the following method in the Context-aware class.

inline fun Context.notification(channelId: String, func: NotificationCompat.Builder.() -> Unit): Notification {
    val builder = NotificationCompat.Builder(this, channelId)
    builder.func()
    return builder.build()
}

2. Extension function to send local broadcast async

The local broadcast manager comes into the picture if you want to share data between your app components. It is more efficient than sending the global broadcast through the system.

fun Context.sendLocalBroadcast(intent: Intent) {
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}

The above sendBroadcast method broadcast the given intent to all interested BroadcastReceivers.

3. EXTENSION FUNCTION TO SEND LOCAL BROADCAST SYNC

Android OS supports two types of broadcast events async and sync. The previous one is async and the one we’re going to see is the sync. You can see the difference between these methods here on this link.

fun Context.sendLocalBroadcastSync(intent: Intent) {
    LocalBroadcastManager.getInstance(this).sendBroadcastSync(intent)
}

4. Helper method to see if the particular service is running

This extension function is one of my favorite. Almost in every application, we often need to run background services and before running the service we check that if the particular service already running or not.

fun Context.isServiceRunning(serviceClass: Class<*>): Boolean {
    val className = serviceClass.name
    val manager = activityManager
    return manager.getRunningServices(Integer.MAX_VALUE)
            .any { className == it.service.className }
}

The activityManager also an extension to Android Context class, we’ll see it’s implementation in a couple of minutes.

5. Launch chrome custom tabs extension function

Android default WebView mostly did our job if we need to open a url. But if we need to change the toolbar color, enter and exit animations, then the result is rather ugly.

To simplify the experience, there is a new library provides a higher-level interface implementation called Chrome Custom Tabs. Here is the extension function for opening a url in a chrome application.

fun Context.openInBrowser(url: String) {
    try {
        val url = Uri.parse(url)
        val intent = CustomTabsIntent.Builder()
                .setToolbarColor(getResourceColor(R.attr.colorPrimary))
                .build()
        intent.launchUrl(this, url)
    } catch (e: Exception) {
        toast(e.message)
    }
}

6. Enqueue the Worker (WorkManager) with kotlin extension function

With the following extension function, we can directly enqueue the worker to WorkManager instance.

inline fun<reified W : ListenableWorker> Context.enqueueWorker(func: OneTimeWorkRequest.Builder.() -> Unit) {
    val builder = OneTimeWorkRequestBuilder<W>()
    builder.func()
    val workerRequest = builder.build()
    WorkManager.getInstance(this.applicationContext).enqueue(workerRequest)
}

// Here's how to call the above method
class MyActivity : AppCompatActivity() {

     override fun onCreate(savedInstanceState: Bundle?) {
         .....
         .....
         enqueueWorker<MyWorker> {
              setInputData()
              setInitialDelay()
         }
     }
}

7. Helper Variable’s to get system services

Functionally exposed by the application framework APIs communicates with system services to access the underlying hardware. There are system services such as PowerManager, NetworkManager, ConnectivityManager, NotificationManager, etc. Here are the extensions in order to access these services.

val Context.notificationManager: NotificationManager
    get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val Context.connectivityManager: ConnectivityManager
    get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

val Context.powerManager: PowerManager
    get() = getSystemService(Context.POWER_SERVICE) as PowerManager

val Context.activityManager : ActivityManager = 
     get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager 

8. Checking runtime permission with extension function

Checking runtime permission’s with kotlin extension function I already described in my previous article.

9. Different helper methods to show a toast

Showing toast is the most basic thing in Android and here is a couple of cool extension function.

fun Context.toast(@StringRes resource: Int, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, resource, duration).show()
}

fun Context.toast(text: String?, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, text.orEmpty(), duration).show()
}

10. Get ContextCompat drawable and color helper method

One last trick for ya, and it really is a cool one. Ever needed to get a drawable or color from ContextCompat class and it really bothers every time to pass the Context instance. Don’t worry I got you on this.

fun Activity.drawable(@DrawableRes drawableResource: Int): Drawable? =
    ContextCompat.getDrawable(this, drawableResource)

fun Activity.color(@ColorRes color: Int) = ContextCompat.getColor(this, color)

Thanks for reading!

So there you have it, ten cool Android context kotlin extension functions–hopefully you’ve found something useful for your next project.

Kotlin very diverse and well-developed language. Please share any of your own favorite extension function by leaving a response below.

Also, if you liked the article don’t forget to hit the ♥️  button below. To get updates for my new stories, subscribe to my website at home page.

Thank you for being here and keep reading…

Write A Comment