mohamed nada mohamed nada - 15 days ago 6
Android Question

How to play a mediaplayer in the background while controlling it with a service/activty?

I am a developing an app which runs mp3 files, I want the app to run the mp3 files after the activity is closed, In which case I used a service but I want to connect the activity with the media player to display seekbar progress and stop and play the media player from the activity, I tried to use broadcasting between the service and activity but it seems to cost a lot of resources, Is there a better way to to this?

Here is a part of how I done that

public class Reciver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
int command = intent.getExtras().getInt("command");
if (command == 0) {
progressDialog.setMessage("loading...");
progressDialog.show();
}

if (command == 1) {
int value = intent.getExtras().getInt("value");
seekBar.setMax(value);
int seconds = (value / 1000) % 60;
int minutes = ((value / (1000 * 60)) % 60);
int hours = ((value / (1000 * 60 * 60)) % 24);
if (hours != 0) {
if (seconds < 10) {
durationTV.setText(hours + ":" + minutes + ":0" + seconds);
} else {
durationTV.setText(hours + ":" + minutes + ":" + seconds);
}

} else {
if (seconds < 10) {
durationTV.setText(minutes + ":0" + seconds);
} else {
durationTV.setText(minutes + ":" + seconds);
}
}

progressDialog.dismiss();
}

if (command == 2) {
int currentDuration = intent.getExtras().getInt("value");
if(!movingSeekBar) seekBar.setProgress(currentDuration);


int seconds = (currentDuration / 1000) % 60;
int minutes = ((currentDuration / (1000 * 60)) % 60);
int hours = ((currentDuration / (1000 * 60 * 60)) % 24);

if (hours != 0) {
if (seconds < 10) {
currentPositionTV.setText(hours + ":" + minutes + ":0" + seconds);
} else {
currentPositionTV.setText(hours + ":" + minutes + ":" + seconds);
}

} else {
if (seconds < 10) {
currentPositionTV.setText(minutes + ":0" + seconds);
} else {
currentPositionTV.setText(minutes + ":" + seconds);
}
}

}

if (command == 3) {
bufferPercent = intent.getExtras().getInt("value");

seekBar.setSecondaryProgress(bufferPercent);

Log.d("Media Player", "" + bufferPercent);
}
}


}

I don't think that the receiver was efficient plus I had another receiver on my service as well, How to play the music in the background while controlling the media player from the activity/service

Answer

use "bound service" then, most likely it is going to be a "bound local service", more info on this pattern can be found here