简体   繁体   中英

communication between two services by Broadcasts

I try to send some data between two services using Broadcasts. The problem is: my Broadcast Receiver class don't get the data (Not getting any data from the sender) and I don't know why. I would appreciate any help. Thanks.

Receiver -

public class Background extends Service  {

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return super.onStartCommand(intent, flags, startId);
}

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra(ActivityRecognizedService.LOCAL_BROADCAST_EXTRA);
        Log.e(TAG,message);
    }
}

Sender -

public class ActivityRecognizedService extends Service {

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return super.onStartCommand(intent, flags, startId);
}

private void handleDetectedActivities(List<DetectedActivity> probableActivities) {

    Intent intent = new Intent(LOCAL_BROADCAST_NAME);
    intent.putExtra(LOCAL_BROADCAST_EXTRA, str.toString());
    //LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    sendBroadcast(intent);
}

You need register your receiver in onStartCommand . Something like, registerReceiver(new MyReceiver(),new IntentFilter(LOCAL_BROADCAST_NAME))

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