Creating an IntentService

Create a subclass of the IntentService called ReminderService. You will have to override the onHandleIntent() method to well, handle the Intent. Then, you would build a Notification instance to notify the user that the reminder is due:

import android.app.IntentService
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.support.v4.app.NotificationCompat
import android.util.Log

class
AlarmService : IntentService("ToDoListAppAlarmReceiver") {
private var context: Context? = null

override fun onCreate() {
super.onCreate()
context = applicationContext
}

override fun onHandleIntent(intent: Intent?) {
intent?showNotification(it)

if(null == intent){
Log.d("AlarmService", "onHandleIntent( OH How? )")
}
}

private fun showNotification(taskDescription: String) {
Log.d("AlarmService", "showNotification($taskDescription)")
val CHANNEL_ID = "todolist_alarm_channel_01"
val mBuilder = NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notifications_active_black_48dp)
.setContentTitle("Time Up!")
.setContentText(taskDescription)

val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(23, mBuilder.build())
}
}

Stepping through the code, this is what you just did:

In the onCreate(), you saved an instance of the applicationContext for later use.

In onHandleIntent(), you used the Kotlin safety check feature to ensure you call the showNotification() method on a non-null instance.

In showNotification(), you used the NotificationCompat builder to create a Notification instance. You set the title and content for the notification as well. Then, using a NotificationManager, you triggered the notification. The ID parameter in the notify() method is an identification for this notification unique to your application.

You need to register the service too. Here is how:

<service android:name=".AlarmService"
android:exported="false"/>

You should be familiar with this, except for android:exported. That just means we are disallowing any external application from interacting with this service.

Here are a few important limitations to note about the IntentService class.

  • It can't interact directly with your user interface. To put its results in the UI, you have to send them to an Activity.
  • Work requests run sequentially. If an operation is running in an IntentService, and you send it another request, the request waits until the first operation is finished.
  • An operation running on an IntentService can't be interrupted.

It is now time to run your app. The alarm should fire and you should see a notification indicating that.

There are other ways to send notifications to your app. Keep reading to learn about push notifications.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset