所有可能阻止媒体播放器的原因

时间:2017-10-18 13:08:56

标签: android service android-mediaplayer

我的Mediaplayer存在一些问题。它运作良好,但在某些神秘的情况下,它停止播放。所以我把一些日志放在onCompletion和onError回调中并用try / catch包围它,但当它停止时,没有任何日志触发。所以我的问题是Mediaplayer如何停止播放并且不会触发此日志。 附:它在服务中播放,但我检查 - 服务继续运行,我也尝试在单件类和GCMService中播放它 - 它仍然停止,我无法弄清楚为什么。 这是我的代码。

public class AlertService extends Service {

private boolean isPlaying = false;
private MediaPlayer mp;

private final String TAG = "Alert_playing";
public static final String PLAY_ALERT_ACTION = "play_alert_service";

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent,  int flags, int startId) {

    if(intent!=null&&intent.getAction().equals(PLAY_ALERT_ACTION)){
        playAlertSound();
    }

    return START_NOT_STICKY;
}

public void playAlertSound() {
    if (!isPlaying) {
        isPlaying = true;
        Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
        mp = new MediaPlayer();
        Uri ringtone = Uri.parse("android.resource://" + RetailerApplication.getAppContext().getPackageName() + "/" + R.raw.alert);
        try {
            mp.setDataSource(RetailerApplication.getAppContext(), ringtone);
            mp.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mp.release();
                            isPlaying = false;
                            stopSelf();
                            Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
                        }
                    });

                }
            });
            mp.prepareAsync();
            mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    isPlaying = false;
                    stopSelf();
                    Log.d(TAG, "what: " + what + " extra: " + extra);
                    Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
                    return false;
                }
            });


        } catch (IOException e) {
            isPlaying = false;
            stopSelf();
            Log.d(TAG, "isPlaying: " + String.valueOf(isPlaying));
            Log.d(TAG, "exception" + e);
            Logger.e(TAG, e);
        }
    } else {
        Log.d(TAG, "miss");
    }
    }
}

0 个答案:

没有答案