package com.example.broadcasts
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// This method is called when the BroadcastReceiver is receiving an Intent broadcast.
TODO("MyReceiver.onReceive() is not implemented")
}
}
MainActivity.kt looks like:
package com.example.broadcasts
import android.content.BroadcastReceiver
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
val br: BroadcastReceiver = MyReceiver()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val filter = IntentFilter("android.intent.action.AIRPLANE_MODE").apply {
addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
}
registerReceiver(br, filter)
}
fun onClick(view: View) {
sendBroadcast(Intent(this, MyReceiver::class.java).setAction("MyAction"))
}
}
With code:
fun onClick(view: View) {
sendBroadcast(Intent(this, MyReceiver::class.java).setAction("MyAction"))
}
In this example I want to start foreground service, and change text in TextView in MainActivity.
First in Android Studio go to File -> New -> Service -> Service and add a service:
In AndroidManifest.xml add FOREGROUND_SERVICE permission:
22023-04-04 * ENDOFUPDATE *
Then in service, in my example that is app\src\main\java\com\milosev\startforegroundserviceandbroadcastreceiver\MyService.kt, override onCreate, and the code so that onCreate looks like:
override fun onCreate() {
super.onCreate()
sendBroadcastMessage("test")
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId)
val notification = notificationBuilder.setOngoing(true)
.setContentTitle("test")
.setContentText("test")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(1)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
Where sendBroadcastMessage looks like:
private fun sendBroadcastMessage(message: String) {
val intent = Intent("")
intent.putExtra("message", message)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
and createNotificationChannel:
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String {
val chan = NotificationChannel(
channelId,
channelName, NotificationManager.IMPORTANCE_NONE
)
chan.lightColor = Color.RED
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
Now MyService.kt looks like:
package com.milosev.startforegroundserviceandbroadcastreceiver
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.location.Location
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
class MyService : Service() {
override fun onBind(intent: Intent): IBinder {
TODO("Return the communication channel to the service.")
}
override fun onCreate() {
super.onCreate()
sendBroadcastMessage("test")
val channelId =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createNotificationChannel("my_service", "My Background Service")
} else {
// If earlier version channel ID is not used
// https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
""
}
val notificationBuilder = NotificationCompat.Builder(this, channelId)
val notification = notificationBuilder.setOngoing(true)
.setContentTitle("test")
.setContentText("test")
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(1)
.setCategory(Notification.CATEGORY_SERVICE)
.build()
startForeground(101, notification)
}
@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String {
val chan = NotificationChannel(
channelId,
channelName, NotificationManager.IMPORTANCE_NONE
)
chan.lightColor = Color.RED
chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
service.createNotificationChannel(chan)
return channelId
}
private fun sendBroadcastMessage(message: String) {
val intent = Intent("")
intent.putExtra("message", message)
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
}
}
In MainActivity.kt in onCreate I have added:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
val textView = findViewById<TextView>(R.id.textView)
textView.text = "test"
}
}
LocalBroadcastManager.getInstance(this)
.registerReceiver(broadCastReceiver, IntentFilter(""))
}
Button click function should look like:
@RequiresApi(Build.VERSION_CODES.O)
fun startForegroundServiceAndBroadcastReceiverClick(view: View) {
val intent = Intent(this,MyService::class.java)
startForegroundService(intent)
}