69 lines
2.3 KiB
Kotlin
69 lines
2.3 KiB
Kotlin
package com.logitech.vc.kirbytest
|
|
|
|
import android.app.NotificationChannel
|
|
import android.app.NotificationManager
|
|
import android.app.PendingIntent
|
|
import android.app.Service
|
|
import android.content.Context
|
|
import android.content.Intent
|
|
import android.os.Build
|
|
import android.os.IBinder
|
|
import androidx.core.app.NotificationCompat
|
|
import androidx.core.content.ContextCompat
|
|
|
|
class BLEService : Service() {
|
|
private val CHANNEL_ID = "BLEService Kotlin"
|
|
|
|
companion object {
|
|
|
|
fun startService(context: Context, message: String) {
|
|
val startIntent = Intent(context,
|
|
BLEService::class.java)
|
|
startIntent.putExtra("inputExtra", message)
|
|
ContextCompat.startForegroundService(context, startIntent)
|
|
}
|
|
|
|
fun stopService(context: Context) {
|
|
val stopIntent = Intent(context, BLEService::class.java)
|
|
context.stopService(stopIntent)
|
|
}
|
|
}
|
|
|
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
|
|
|
//do heavy work on a background thread
|
|
val input = intent?.getStringExtra("inputExtra")
|
|
createNotificationChannel()
|
|
val notificationIntent = Intent(this, MainActivity::class.java)
|
|
|
|
val pendingIntent: PendingIntent =
|
|
Intent(this, MainActivity::class.java).let { notificationIntent ->
|
|
PendingIntent.getActivity(this, 0, notificationIntent,
|
|
PendingIntent.FLAG_IMMUTABLE)
|
|
}
|
|
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
|
|
.setContentTitle("BLEService Service Kotlin Example")
|
|
.setContentText(input)
|
|
//.setSmallIcon(R.drawable.ic_notification)
|
|
.setContentIntent(pendingIntent)
|
|
.build()
|
|
|
|
startForeground(1, notification)
|
|
//stopSelf();
|
|
return START_NOT_STICKY
|
|
}
|
|
|
|
override fun onBind(intent: Intent): IBinder? {
|
|
return null
|
|
}
|
|
|
|
private fun createNotificationChannel() {
|
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
|
val serviceChannel = NotificationChannel(CHANNEL_ID, "BLEService Service Channel",
|
|
NotificationManager.IMPORTANCE_DEFAULT)
|
|
|
|
val manager = getSystemService(NotificationManager::class.java)
|
|
manager!!.createNotificationChannel(serviceChannel)
|
|
}
|
|
}
|
|
} |