In File -> New -> Other -> BroadCastReceiver I have added BroadCastReceiver receiver class, and in manifest I have added for example:
<action android:name="android.intent.action.AIRPLANE_MODE"/>
Now my AndroidManifest.xml looks like:
<?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.broadcasts">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Broadcasts"
tools:targetApi="31">
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.AIRPLANE_MODE"/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Where MyReceiver.kt looks like:
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"))
}
I am sending my own "MyAction"