Skip to content

Instantly share code, notes, and snippets.

@sajjadyousefnia
Created July 3, 2024 02:43
Show Gist options
  • Save sajjadyousefnia/e0cada7289afc2fe63254c514b6592d5 to your computer and use it in GitHub Desktop.
Save sajjadyousefnia/e0cada7289afc2fe63254c514b6592d5 to your computer and use it in GitHub Desktop.
class AlarmService : Service() {
val TAG = "AlarmService"
private val INTERVAL_TIME = 60L * 1000L
private val messenger = Messenger(IncomingHandler())
private val binder = LocalBinder()
override fun onBind(intent: Intent?): IBinder? {
return binder
}
@SuppressLint("MissingPermission")
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
createNotification()
return START_STICKY
}
private inner class IncomingHandler : Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message) {
// Handle messages from Activity
Toast.makeText(this@AlarmService, msg.data.getString("msg"), Toast.LENGTH_LONG).show()
}
}
inner class LocalBinder : Binder() {
fun getService(): AlarmService = this@AlarmService
fun getMessenger(): Messenger = messenger
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_HIGH
val serviceChannel = NotificationChannel(
"NOTIFICATION_CHANNEL", "My Service Channel", importance
)
val manager = getSystemService(NotificationManager::class.java)
manager?.createNotificationChannel(serviceChannel)
}
}
private fun createNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel()
}
val CHANNEL_ID = "my_app"
val NOTIFICATION_ID = 1
val notificationIntent = Intent(this, SecondActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, FLAG_IMMUTABLE)
val notification =
NotificationCompat.Builder(this, CHANNEL_ID).setContentTitle("Service Running")
.setContentText("Your service is running in the background").setPriority(
NotificationCompat.PRIORITY_DEFAULT
).setForegroundServiceBehavior(NotificationCompat.FOREGROUND_SERVICE_IMMEDIATE)
.setSmallIcon(R.drawable.common_google_signin_btn_icon_dark)
.setContentIntent(pendingIntent).build()
startForeground(NOTIFICATION_ID, notification)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment