Reputation: 25
I'm building an Android app in Kotlin. The app contains a stopwatch. I have a service class (TimerService) that correctly executes task every second (log appears):
private inner class MyTask(private var time: Double) : TimerTask() {
override fun run(){
Log.d("SERVICE", time.toString())
val intent = Intent(TIMER_UPADATED)
time++
intent.putExtra(TIME_EXTRA, time)
sendBroadcast(intent)
}
}
However, the receiver (below) doesn't receive anything (log doesn't appear):
registerReceiver(
timeReceiver, IntentFilter(TimerService.TIMER_UPADATED)
)
private val timeReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
time = intent.getDoubleExtra(TimerService.TIME_EXTRA, 0.0)
Log.d("RECEIVER", time.toString())
}
}
I think the receiver might be incorrectly registered. According to tutorials this should work:
registerReceiver(
timeReceiver, IntentFilter(TimerService.TIMER_UPADATED)
)
But this implementation of registerReceiver seems to be deprecated now and from debugging it seems like this is the correct version:
registerReceiver(
requireContext(), updateTime, IntentFilter(TimerService.TIMER_UPADATED),
ContextCompat.RECEIVER_NOT_EXPORTED
)
The latter doesn't receive.
SDK in build.gradle file:
android {
namespace = "com.myapp.myapp"
compileSdk = 34
defaultConfig {
applicationId = "com.myapp.myapp"
minSdk = 33
targetSdk = 34
Upvotes: 0
Views: 56
Reputation: 959
Try setting a package name to your broadcast intent like:
val intent = Intent(TIMER_UPADATED)
time++
intent.putExtra(TIME_EXTRA, time)
intent.setPackage(packageName) // <-- add this line
sendBroadcast(intent)
Upvotes: 0