I have created a background stream music playing service for one of my project. It's works correctly but when playing I got a call and the media didn't stopped like in other apps. Also when I answered the call music still played.
package mypackage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.widget.Toast;
import mypackage.R;
public class StreamPlayer extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
Notification noti;
android.support.v4.app.NotificationCompat.Builder noticom;
NotificationManager notiman;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Toast.makeText(StreamPlayer.this, "Buffering", Toast.LENGTH_LONG).show();
}
});
try {
mediaPlayer.setDataSource("http://149.56.185.83:8138/stream");
mediaPlayer.prepare();
}catch (Exception ex){
}
mediaPlayer.setOnCompletionListener(this);
noticom = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setCategory(MEDIA_SESSION_SERVICE)
.setAutoCancel(true)
.setContentTitle("Sample Streamed Music Player")
.setOngoing(true)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentText("Now Playing")
.setCategory(NotificationCompat.CATEGORY_EVENT);
notiman = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
Toast.makeText(StreamPlayer.this, "Now Playing", Toast.LENGTH_SHORT).show();
noti = noticom.build();
notiman.notify(2017,noti);
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
noticom.setOngoing(false);
noticom.setContentText("Stopped");
Toast.makeText(StreamPlayer.this, "Stopped", Toast.LENGTH_SHORT).show();
noti = noticom.build();
notiman.notify(2017,noti);
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
Does any one know how to fix that?