Skip to content

Instantly share code, notes, and snippets.

@brendan-fahy
Created January 28, 2017 18:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendan-fahy/d30e17e1aef68256d31a97c3ec7ed97b to your computer and use it in GitHub Desktop.
Save brendan-fahy/d30e17e1aef68256d31a97c3ec7ed97b to your computer and use it in GitHub Desktop.
class AlarmReceiver: BroadcastReceiver() {
val TAG = "AlarmManager"
override fun onReceive(context: Context, intent: Intent) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE)
as NotificationManager
val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
val batteryStatus = context.registerReceiver(null, intentFilter)
Log.d(TAG, "onReceive: sending notification with battery level " +
"${batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)}")
notificationManager.notify(Constants.NOTIFICATION_ID,
buildNotification(context, batteryStatus))
}
private fun buildNotification(context: Context, batteryStatus: Intent): Notification {
val level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
return NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentText("Phone is $level% charged.")
.setSmallIcon(R.mipmap.ic_launcher)
.setOnlyAlertOnce(true)
.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment