Reputation: 2886
I've made a functional android application that implements MediaPlayer
and I know it's late now but better now than never, I want to implement a service to be able to play media while multitasking
on other applications.
Is there a way how can I pass for example an ArrayList
of String
from activity to the service
? What I have found were information about Custom Objects
that are passed through parcelable
which I think is not needed.
For example, how I've started my transition:
public class PlayerService extends Service implements MediaPlayer.OnPreparedListener{
private static final String ACTION_PLAY = "action.PLAY";
private static final String ACTION_PAUSE = "action.PAUSE";
private MediaPlayer mediaPlayer = null;
@Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
try {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.reset();
mediaPlayer.setDataSource(musicUrl.get(position));
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
// setCurrentSong(myDataList.get(position));
// morphButton.setState(MorphButton.MorphState.START);
//
// setHighlight(myDataList.get(currentPosition));
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onPrepared(MediaPlayer mp) {
}
}
As you can see, I need to get from an ArrayList
the music URL to prepare de MediaPlayer
Upvotes: 2
Views: 2016
Reputation: 43334
In your activity, where you bind to the service you can add an ArrayList<String>
via the intent:
ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
ArrayList<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("b");
Intent i = new Intent(this, BLEDiscoveryService.class);
i.putStringArrayListExtra("list", stringList);
bindService(new Intent(this, MyService.class), serviceConnection, BIND_AUTO_CREATE);
And in your service's onBind()
you can retrieve it from the passed intent.
public class LocalBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
@Override
public void onCreate() {
super.onCreate();
binder = new LocalBinder();
}
@Override
public IBinder onBind(Intent intent) {
ArrayList<String> stringList = intent.getStringArrayListExtra("list");
return binder;
}
Upvotes: 2