Home > Software engineering >  how can i use broadcast receiver in my application
how can i use broadcast receiver in my application

Time:07-23

im trying use broadcast receivers. my manifest and BR class es here. When I press text I expect it to say "receiver worked". but it is not working. it just says "button pressed". and stackoverflow expects me to write something

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.mybroadcastreceiver">

    <application
        .
        .
        .
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".MyFirstReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="MyReceiver"></action>
            </intent-filter>
        </receiver>
    </application>

</manifest>
class MyFirstReceiver : BroadcastReceiver(){
    override fun onReceive(p0: Context?, p1: Intent?) {
        println("Receiver çalıştı")
    }
}
class MainActivity : AppCompatActivity() {

    lateinit var binding : ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    fun myFunc(view : View){
        sendBroadcast(Intent("MyReceiver"))
        println("Butona basıldı")
    }
}

CodePudding user response:

From the documentation:

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.

You are using an implicit broadcast here. You need to make your broadcast explicit, which you can do either by specifying your package name or the exact component in the broadcast Intent, like this:

sendBroadcast(Intent(this, MyReceiver::class.java))

or

val intent = Intent("MyReceiver").apply {
    setPackage("com.example.mybroadcastreceiver")
}
sendBroadcast(intent)
  • Related