Copyright — https://redfoxsec.com/wp-content/uploads/2022/11/exploiting-broadcast-receivers-thumb.png

Broadcast Receiver — Android Development

Shivansh Seth

--

Android apps can send or receive broadcast messages from the Android system and other Android apps, similar to the publish-subscribe design pattern. These broadcasts are sent when an event of interest occurs.

Generally speaking, broadcasts can be used as a messaging system across apps and outside of the normal user flow.

1. Static BR

Broadcast Recievers are used to check if any service is in use or not.

To create a new BR Component go to New > Other > Broadcast Receiver

AndroidManifest.xml

<receiver
android:name=".LocaleChangedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name = "android.intent.action.LOCALE_CHANGED"/>
</intent-filter>
</receiver>

MainActivity.kt

package com.example.broadcastreceiverapp

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast
class LocaleChangedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Log.d("RCV", "LOCALE")
Toast.makeText(context, "Language Changed", Toast.LENGTH_SHORT).show()
context.startActivity(Intent(context, MainActivity::class.java))
}
}

2. Dynamic BR

MainActivity.kt

package com.example.broadcastreceiverapp

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val psr = PowerStateReceiver()
val ifilter: IntentFilter = IntentFilter().apply {
addAction(Intent.ACTION_POWER_DISCONNECTED)
addAction(Intent.ACTION_POWER_CONNECTED)
}
registerReceiver(psr, ifilter)
}
inner class PowerStateReceiver : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
Toast.makeText(this@MainActivity, "Charging State Changed", Toast.LENGTH_SHORT).show()
}
}
}

This condition is not working well with Samsung atleast. Further research pending.

if(intent.action == null) return
if(intent.action == Intent.ACTION_POWER_DISCONNECTED) {
Toast.makeText(
this@MainActivity,
"Kyu Utara Charger?",
Toast.LENGTH_SHORT
).show()
}
if(intent.action == Intent.ACTION_POWER_CONNECTED){
Toast.makeText(
this@MainActivity,
"Sahi kiya lga ke!",
Toast.LENGTH_SHORT
).show()
}

Resources

Refer to the below resources to get in-depth knowledge about the Broadcast Receivers :

Broadcast Receiver in Android With Example — GeeksforGeeks

Broadcast Receiver in android | Android | Kotlin | Himanshu Gaur |

I will surely be adding the Application for it, whenever it gets ready.

--

--