Reality
Reality

Reputation: 17

When I press back music get stopped

I have created a stream Music player. But I have some minor Problems With my app When I play music and press back then the music gets stopped please tell me the solution to this problem and I have 1 more problem.Please tell me what I do when the song is finished it does not play next song automatically. And When the song is finished then I was trying to play next song then app gets stopped. here is my code

  public void get()
{
    seekBarProgress.setMax(99); // It means 100% .0-99
    seekBarProgress.setOnTouchListener(this);
    mMediaPlayer.setOnBufferingUpdateListener(this);
    mMediaPlayer.setOnCompletionListener(this);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            //getting the upload
            Upload upload = uploadList.get(i);

            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
                mMediaPlayer.reset();
                seekBarProgress.setProgress(0);
            }

            try {
                mMediaPlayer.setDataSource(upload.getUrl());
                mMediaPlayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
}
   private void primarySeekBarProgressUpdater() {
    seekBarProgress.setProgress((int)(((float)mMediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100));
    if (mMediaPlayer.isPlaying()) {
        Runnable notification = new Runnable() {
            public void run() {
                primarySeekBarProgressUpdater();
            }
        };
        handler.postDelayed(notification,1000);
    }
}

 @Override
    public boolean onTouch(View v, MotionEvent event) {
     if(v.getId() == R.id.length){
          if(mMediaPlayer.isPlaying()){
            SeekBar sb = (SeekBar)v;
            int playPositionInMillisecconds = (mediaFileLengthInMilliseconds 
     / 100) * sb.getProgress();
           mMediaPlayer.seekTo(playPositionInMillisecconds);
        }
    }
    return false;
}
@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {

    seekBarProgress.setSecondaryProgress(percent);
}
@Override
public void onCompletion(MediaPlayer mp) {
// Help me also here 

}
 private void togglePlayPause() {
    if (mMediaPlayer.isPlaying()) {
        mMediaPlayer.pause();
        mPlayerControl.setImageResource(R.drawable.ic_play);
         } else {
        mMediaPlayer.start();
        mPlayerControl.setImageResource(R.drawable.ic_pause);
        mediaFileLengthInMilliseconds = mMediaPlayer.getDuration();
        primarySeekBarProgressUpdater();
        mSelectedTrackImage.setImageResource(R.drawable.images);
    }
}

if anyone knows then please help me.

Upvotes: 0

Views: 52

Answers (1)

Northern Poet
Northern Poet

Reputation: 2045

Your player code executes inside the Activity, and when Back button pressed, activity goes to background, playing stops.

The correct solution is to create an Android service, briefly:

public class PlayerService extends Service implements AudioManager.OnAudioFocusChangeListener {
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent.getAction();
        if (PLAY.equals(action))
            play()
        ...
    }

Register it in androidManifest:

<service
    android:name=".PlayerService"
    android:exported="false" >
</service>

and start it, for example in in onCreate of your Application class:

@Override
public void onCreate() {
    super.onCreate();

    startService(new Intent(this, PlayerService.class));
    bindService(new Intent(this, PlayerService.class), mConnection, Context.BIND_AUTO_CREATE);
}

Please refer to this article for creating services: https://developer.android.com/training/run-background-service/create-service.html

Answering to your second question, you was right thinking on override onCompletion method. As usual it should looks like this (in pseudocode):

@Override
public void onCompletion(MediaPlayer mp) {
    if (isRepeat) {
        play(current);
    } else if (isShuffle) {
        play(random);
    } else {
        play(next);
    }
}

public void  play(index or file or stream){
    mp.reset();
    mp.setDataSource(get by index or file or stream);
    mp.prepare();
    mp.start();
}

Upvotes: 1

Related Questions