MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Log.i("MyReceiver", "MyAction received!");
}
}
In AndroidManifest.xml
(under the application
tag)
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="MyAction" />
</intent-filter>
</receiver>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sendBroadcast(new Intent("MyAction"));
}
}
MyReceiver.onReceive
method is never triggered.
Did I miss something?
In Android 8 onwords
Example :
Below Android 8
Then you have to use an explicit
Intent
, one that identifies the receiver, such as:The string itself does not matter, just need to be the same in all places and unique, I use fully qualified name of the constant.
The receiver:
To broadcast the intent:
In Kotlin