简体   繁体   中英

Android MediaPlayer stops after playing 1 minute in background

I am playing an audio stream from mediaPlayer using a service but it stops playing the song after approx one minute of being in the background or the screen turned off. While on the other hand it works fine and completes the song when the appication is kept open.

public class MyService extends Service implements MediaPlayer.OnPreparedListener {
    MediaPlayer mediaPlayer = null;
    String audio_stream;
    Context context;

    public int onStartCommand(Intent intent, int flags, int startId) {
        audio_stream = intent.getStringExtra("url");
        mediaPlayer = new MediaPlayer();

        try {
            mediaPlayer.setDataSource(audio_stream);
        } catch (IOException e) {
            //e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        mediaPlayer.setOnPreparedListener(this);

        mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {

                return false;
            }
        });
        return START_STICKY;
    }

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



    @Override
    public void onPrepared(MediaPlayer mp) {
        Log.d("Channel", audio_stream+"he");
        mp.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }else{
            Log.d("channel", "this is the case");
        }

    }




    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mediaPlayer.release();
    }
}

Before MediaPlayer stops, it gives 4 lines in the log which are

V/MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null
V/MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null

I am unable to understand where the problem is exactly and how can I proceed to overcome it. Thank you

On Android 8.0 and higher devices, you need to have this be a foreground service , with an associated Notification . Otherwise, your service will be stopped after a minute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM