Answer the question
In order to leave comments, you need to log in
How to fix service performance?
Hello, I have a fragment where music and service are played, so that, when minimized, the music continues to play. I click on the play, it crashes out of the application, and if I remove if (mediaPlayer == null) it starts working, only the pause still stops working, who knows what the problem is?
service:
public class AudioPlaybackService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
public class AudioPlaybackService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener
{
MediaPlayer mediaPlayer;
public static final String EXTRA_AUDIO_URL = "audio_url";
String url;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (mediaPlayer == null){
this.url = intent.getStringExtra(EXTRA_AUDIO_URL);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
else if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
return START_STICKY;
}
@Override
public void onCreate()
{
super.onCreate();
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnCompletionListener(this);
}
@Override
public void onCompletion(MediaPlayer mp)
{
// called when song has ended
}
@Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
@Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
}
Fragment(кнопка паузы и старта):
playPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
serviceIntent.putExtra(AudioPlaybackService.EXTRA_AUDIO_URL, "http://stream3.radiostyle.ru:8003/radioacca");
getActivity().startService(serviceIntent);
Answer the question
In order to leave comments, you need to log in
if (mediaPlayer == null){
this.url = intent.getStringExtra(EXTRA_AUDIO_URL);
try {
mediaPlayer.reset();
It may take some time before the state is updated in calls to isPlaying(), and it can be a number of seconds in the case of streamed content.link .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question