2

Below is my PlayerActivity.java. It has a MediaPlayer which receives the link to be streamed from the previous activity. The MediaPlayer is working fine but when I press back button or lock the screen the player stops. I want the audio to be streamed irrespective of Activity that is running and even when the screen is locked.

PlayerActivity.java

package com.example.telugump3;

import java.io.IOException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class PlayerActivity extends Activity {
private Button btn;
String mname;

/**
 * help to toggle between play and pause.
 */
private boolean playPause;
private MediaPlayer mediaPlayer;
/**
 * remain false till media is not completed, inside OnCompletionListener make it true.
 */
private boolean intialStage = true;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent iin= getIntent();
    Bundle b = iin.getExtras();


    if(b!=null)
    {
        mname =(String) b.getString("song_link");

    }

    setContentView(R.layout.player_activity);
    btn = (Button) findViewById(R.id.button1);
    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    btn.setOnClickListener(pausePlay);

}


private OnClickListener pausePlay = new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        // TODO Auto-generated method stub


        if (!playPause) {
            btn.setBackgroundResource(R.drawable.button_pause);
            if (intialStage)
                new Player()
                        .execute(mname);


            else {
                if (!mediaPlayer.isPlaying())
                    mediaPlayer.start();

            }
            playPause = true;
        } else {
            btn.setBackgroundResource(R.drawable.button_play);
            if (mediaPlayer.isPlaying())
                mediaPlayer.pause();
            playPause = false;

        }
    }


};
/**
 * preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
 * @author piyush
 *
 */

class Player extends AsyncTask<String, Void, Boolean> {
    private ProgressDialog progress;

    @Override
    protected Boolean doInBackground(String... params) {
        // TODO Auto-generated method stub
        Boolean prepared;
        try {

            mediaPlayer.setDataSource(params[0]);

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    intialStage = true;
                    playPause=false;
                    btn.setBackgroundResource(R.drawable.button_play);
                    mediaPlayer.stop();
                    mediaPlayer.reset();
                }
            });
            mediaPlayer.prepare();
            prepared = true;
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            Log.d("IllegarArgument", e.getMessage());
            prepared = false;
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            prepared = false;
            e.printStackTrace();
        }
        return prepared;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        if (progress.isShowing()) {
            progress.cancel();
        }
        Log.d("Prepared", "//" + result);
        mediaPlayer.start();

        intialStage = false;
    }

    public Player() {
        progress = new ProgressDialog(PlayerActivity.this);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
        this.progress.setMessage("Buffering...");
        this.progress.show();

    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    if (mediaPlayer != null) {
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer = null;
    }
}
}
Shahid Roshan
  • 105
  • 3
  • 14
  • It is not possible to do it with the `Activity` instead you should implement a `Service` that handles media playback and bind it to the `Activity` to handle user callbacks – nstosic Mar 31 '15 at 14:37
  • Simply don't release the media player in onPause to keep the music playing – Benyam Ephrem Mar 31 '15 at 14:45
  • Folklow this URL you can get what you want. [http://stackoverflow.com/questions/8209858/android-background-music-service][1] [1]: http://stackoverflow.com/questions/8209858/android-background-music-service – Shadik Khan Mar 31 '15 at 14:53

2 Answers2

1

You can use Service to play audio in the background. I recommend reading Using a Service with MediaPlayer.

Ziem
  • 6,579
  • 8
  • 53
  • 86
0

To have it play all the time, use a Service instead of the Activity.

Dave
  • 4,282
  • 2
  • 19
  • 24
  • will i be able to pause it if i use Service? – Shahid Roshan Mar 31 '15 at 14:40
  • Absolutely. Ziem's link explains most everything (that's why I didn't expound more). You should probably look through the stuff about "bound services" in the Android documentation for `Service`. An `Activity` can bind to the `Service` and call its methods. Simply make a `pause()` method in the `Service` that pauses the actual `MediaPlayer`. – Dave Mar 31 '15 at 15:21
  • When I mention `Activity` there, you will need an `Activity` for when you want UI. Buttons and whatnot live in the `Activity`, the `MediaPlayer` lives in the `Service`. – Dave Mar 31 '15 at 15:22