Search code examples
androidbroadcastreceiverbroadcastandroid-broadcastandroid-broadcastreceiver

My Android broadcast receiver is never triggered


In AndroidManifest.xml I have this:

<receiver android:name=".MyBroadcast"  android:exported="true"/>

My broadcast file:

package com.myapp;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;


public class MyBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent intent1 = new Intent(context, Radio.class);
        intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent1);
    }
}

I am trying to run application after close it to play music in background.


Solution

  • That's because you never specify what intent you're actually listening for.

    You need to register the broadcast receiver to listen for specific broadcasts (events), either in the manifest using the intent-filter tag or dynamically at runtime. See this question for more discussion about the difference.

    Here's an example of how to do this in the manifest (from the linked question):

    <receiver android:name="TestReceiver">
            <intent-filter>
                <action android:name="android.media.AUDIO_BECOMING_NOISY"/>
            </intent-filter>
        </receiver>
    

    This means that the broadcast receiver is listening for the AUDIO_BECOMING_NOISY intent. (You'll want to replace this with a more appropriate intent that reflects when you want this to run).

    There's a very useful list of Intents that you can listen for here. You can select a broadcast from there (or from one of the libraries) or, if you're listening for an event that occurs within your application, you can raise the broadcast yourself.

    Also, make sure that the event in question is actually being raised. If the broadcast you're listening for never happens, the broadcast receiver will never actually be triggered.

    For related reading, see the Observer Pattern (which is the design pattern that Android Broadcast Receivers implement).