Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a custom broadcast action to receivers in manifest?

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?

like image 204
Yairopro Avatar asked Mar 09 '18 15:03

Yairopro


People also ask

What method is used to send a broadcast event?

Android uses Broadcast Intents extensively to broadcast system events like battery-charging levels, network connections, and incoming calls. Broadcasting Intents is actually quite simple. Within your application component, construct the Intent you want to broadcast, and use the sendBroadcast method to send it.


1 Answers

I use Android 8.

Then you have to use an explicit Intent, one that identifies the receiver, such as:

sendBroadcast(new Intent(this, MyReceiver.class).setAction("MyAction"));

See Broacast limitations in Android 8 release docs.

like image 103
CommonsWare Avatar answered Sep 21 '22 05:09

CommonsWare