How to pass a class instance to a service using putExtra

JBoy :

I have a class that uses a class instance of import io.flutter.plugin.common.MethodChannel but now i want to pass that class instance to a Service where i can call it, but i cant get around it.

I have tried using putExtra but i cant seem to find a way to get it from the service end.

For example:

Intent playIntent = new Intent(activity.getApplicationContext(), MusicPlayerService.class);
playIntent.putExtra("activeAudioUrl", activeAudio);
playIntent.putExtra("channelInstance", channel);
activity.startService(playIntent);

Here is the service class from which i am trying to get the data:

public int onStartCommand(Intent intent, int flags, int startId) {
    String activeAudio = intent.getStringExtra("activeAudioUrl");
    MethodChannel methodChannel = intent.getParcelableExtra("channelInstance");

    ...
}
Amin Soheyli :

You should create a class containing your data to be passed and extend/implement that from Serializable or Parcelable and then you can put an object of that class as an Extra to your Intent and use it in your Service. In this class you creat your data, pass them and then retrieve them. For creating your custom Parcelable class you can see these following links:

1.stackoverflow

2.medium

And according to this link it's better to use Parcelable.

So, create a class that implement the Parcelable (e.g. name this class DataToSend), you can use constructor to pass your data and use getter for retrieving your data.

Edit => Now DataToSend is already implements Parcelable and all you have to do is :

Bundle bundle = new Bundle();
DataToSend dataToSend = new DataToSend(activeAudio, channel);
bundle.putParcelable("data", dataToSend);
Intent playIntent = new Intent(activity.getApplicationContext(), 
MusicPlayerService.class);
playIntent.putExtra(bundle);
activity.startService(playIntent);

and for retrieving data :

public int onStartCommand(Intent intent, int flags, int startId) {
    String activeAudio = intent.getStringExtra("activeAudioUrl");
    MethodChannel methodChannel = intent.getParcelableExtra("channelInstance");
    Bundle b = intent.getExtra();
    DataToSend data = (DataToSend) b.getParcelable("data");

    // Here you can retrieve your data(channel & activeAudio) from following
    // data object. (e.g. data.getAudio())
    ...
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166448&siteId=1