내 프로젝트 중 하나에 배경 음악 재생 서비스를 만들었습니다. 작동하지만 재생 중일 때 전화가 걸려서 다른 앱처럼 미디어가 멈추지 않았습니다. 또한 내가 전화에 응답했을 때 음악은 여전히 연주했다.내 Android Java 백그라운드 서비스에서 도움이 필요합니다. 호출이 감지되었을 때 중지하려면
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();
}
}
아무도 그 문제를 해결하는 방법을 알고 있습니까?
Notification notificationFunction(){
Notification.Builder mBuilder = new Notification.Builder(this);
/*customize notification*/
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
return mBuilder.build();
}
이 시도해야 .. http://stackoverflow.com/a/5610996/3544839 – Moinkhan
을 시도 ... .. –
응용 프로그램이 충돌되어 표시됩니다 –