简体   繁体   中英

Android media player stop playing while in background

I'm making music player app with simple functionality. But when I listen music on my phone with Android 6, sometimes music stops playing until I turn on display again with power button. Then next song is playing, so it seems like it's problem with loading next song. I tried to write new app just to test it out, for this purpose I used this tutorial: https://code.tutsplus.com/tutorials/background-audio-in-android-with-mediasessioncompat--cms-27030

To this example I added ArrayList with paths to songs. In mediaPlayer onCompletionListener I increase track counter and load new song to media player.

My code:

    private void initMediaPlayer() {
         mMediaPlayer = new MediaPlayer();
         mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
         mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
         mMediaPlayer.setVolume(1.0f, 1.0f);

         mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
             @Override
             public void onCompletion(MediaPlayer mediaPlayer)
             {
                 onTrackCompletion();
             }
    });

    private void onTrackCompletion()
    {
         NextTrack();
         Play();
    }


    private void NextTrack()
    {
        playlistPosition++;
        if (playlistPosition == playlists.get(playlistCurrent).size){
            playlistPosition = 0;
    }

    sendAction(ACTION_TRACK_NEXT);

    if(mMediaPlayer.isPlaying()){
        Pause();
    }

        loadSong();
        Play();
    }

    private void loadSong()
    {
        String path = playlists.get(playlistCurrent).getPath(playlistPosition);

        if(path == null || path == "")
        {
            return;
        }

        try 
        {

            try 
            {

                mMediaPlayer.setDataSource(path);

            } catch( IllegalStateException e ) {
                mMediaPlayer.release();
                initMediaPlayer();
                mMediaPlayer.setDataSource(path);
            }


            initMediaSessionMetadata();

        } catch (IOException e) {
            return;
        }
        try {
            mMediaPlayer.prepare();
        } catch (IOException e) {}

        sendTrackData();
    }

I don't know anymore why this doesn't work. In manifest I have WAKE_LOCK permission. I also set wake lock for Media player.

Edit: Today I tried to move loading song into onPlayFromMediaId. I made broadcast from AutoActivity where is Media player to Main Activity and send back onPlayFromMediaId with path to song. But seems like this doesn't work either.I also find out that changing volume with buttons also wake up app.

Edit2: I made many tests and added debug string in many places in code. And I found out that app stops at mediaplayer.prepare() until I trigger any action on phone (turn on display, volume up/down, click headset button). But I don't know how to fix this bug. I tried to use prepareAsync, but didn't help.

Unless you use foreground service, the system will kill your process and mediaplayer will stop. below is a part from from a foreground service ( notification example).

builder.setContentTitle(aMessage)                           // required
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentText(this.getString(R.string.app_name))  // required
        .setAutoCancel(false)
        .setContentIntent(pendingIntent)
        .setVibrate(new long[]{0L})
        .setPriority(Notification.PRIORITY_HIGH);
int mId = 1489;
startForeground(mId, builder.build());

The above code is tested and working fine.

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