简体   繁体   中英

Android BroadcastReceiver is never called

Hi all and thank you for your help! I'll start with the code
So, the class with the broadcast receiver is this:

public class MyService extends Service {

    // ...
    // ACTION
    public static final String action = "com.mywebsite.myapp.package.class.action";
    // ...
    public void onCreate() {
        // SET BROADCAST RECEIVER
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.w("broadcast receiver", "action: " + action);
                if (action.equals("**")) {
                    Log.w("broadcast receiver", "**");
                }
            }
        };
        // REGISTER BROADCAST
        final IntentFilter myFilter = new IntentFilter();
        myFilter.addAction(action);
        registerReceiver(this.broadcastReceiver, myFilter);
    }
    // ....
}

And I try to send a broadcast in this way from a fragment

Intent myIntent = new Intent(getActivity()
        .getApplicationContext(), MediaPlayerService.class);
getActivity().startService(myIntent);
myIntent = new Intent(getActivity().getApplicationContext(),
        MediaPlayerService.class);
myIntent.setAction(MyService.action);
myIntent.putExtra("data", "*******");
getActivity().sendBroadcast(myIntent);

However the broadcast receiver is never called. I can say this because of the logcat: the line Log.w("broadcast receiver", "action: " + action); is never called. How can I resolve?

Thank you!

EDIT: class code:

public class MediaPlayerService extends Service {

    private MediaPlayer mediaPlayer = null;
    private AudioManager audioManager;
    private BroadcastReceiver broadcastReceiver;
    private String absoluteFilePath;
    private Boolean areThereAnyErrors = false;
    private int savedVolume;
    // ACTIONS
    public static final String prepareAndPlayNewFile = "com.disgustingapps.player.AudioManagement.MediaPlayerService.prepareAndPlayNewFile";

    @Override
    public void onCreate() {
        Log.w("MediaPlayerService", "onCreate called");
        // SET BROADCAST RECEIVER
        broadcastReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                Log.w("broadcast receiver", "action: " + action);
                if (action.equals("prepareAndPlayNewFile")) {
                    Log.w("broadcast receiver", "prepareAndPlayNewFile");
                    prepareAndPlayNewFile(intent
                            .getStringExtra("absoluteFilePath"));
                }
            }
        };
        // REGISTER BROADCAST
        final IntentFilter myFilter = new IntentFilter();
        myFilter.addAction(prepareAndPlayNewFile);
        registerReceiver(this.broadcastReceiver, myFilter);
    }

    @Override
    public void onDestroy() {
        Log.w("MediaPlayerService", "onDestroy called");
        unregisterReceiver(broadcastReceiver);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.w("MediaPlayerService", "onStartCommand called");
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }

    public void prepareAndPlayNewFile(String absoluteFilePath) {
        // ...do something...
    }
}

Without seeing the code for the service and how its started its hard to tell where the issue is..

First, you're registering the receiver in the onCreate of the service but you dont have an unregister event.. You should put the broadcast receiver in the global scope of your service class and unregister in onDestroy() (Override onDestroy and log a message to confirm its stopping)

Second unless you bind to the service then the service will "Stop" as soon as the commands in the startup execute.

You should override onStartCommand and return START_STICKY to keep the service running.

The reason you are not receiving the Intent is because the receiver is in onCreate() . context.startService() will only pass the Activity 's Intent to the Service 's onStartCommand() . The Service has already been created by then (or should have), so trying to receive in onCreate() will never work.

More info here

Trying to receive in onStartCommand() will only work once (guess). But having a BroadcastReceiver in onStartCommand will only get you the data if you call startService() . Since you are calling this anyway, it's far easier just do ditch the BroadcastReceiver and just pass the data with the Intent delivered to the Service s onStartCommand() .

EDIT

@Override
public void onCreate() {
    Log.w("MediaPlayerService", "onCreate called");
}

@Override
public void onDestroy() {
    Log.w("MediaPlayerService", "onDestroy called");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.w("MediaPlayerService", "onStartCommand called");     

    String action = intent.getAction();
    Log.w("onStartCommand()", "action: " + action);

    if (action.equals("prepareAndPlayNewFile")) {
       prepareAndPlayNewFile(intent.getStringExtra("absoluteFilePath"));
    }

    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.   
    return START_STICKY;
}

Then just do this:

Intent myIntent = new Intent(getActivity().getApplicationContext(), MediaPlayerService.class);
myIntent.setAction("prepareAndPlayNewFile");
myIntent.putExtra("absoluteFilePath", "/path/");
startService(myIntent);

startService() :

Every call to this method will result in a corresponding call to the target service's onStartCommand(Intent, int, int) method, with the intent given here. This provides a convenient way to submit jobs to a service without having to bind and call on to its interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM