Losing the control of the mediaplayer when the activity is recreated - android

In my project I am trying to make a media player which plays a shoutcast stream. Everything seemed to be working well until I pressed the back button on my device, which I think stops the activity and causes the device to recreate the activity when launched again. The problem is , when the activity is recreated , I lose the control of the mediaplayer and a new mediaplayer is created.
I need to be able to have the mediaplayer's control back at that point. How is it possible?
This part of code belongs to onCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
if (mediaPlayer == null){
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getString(R.string.yayin));
} catch (Exception e) {
e.printStackTrace();
}
mediaPlayer.prepareAsync();
}
if(!isPlaying){
btn.setBackgroundResource(R.drawable.oynat);
}
else{
btn.setBackgroundResource(R.drawable.durdur);
}
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isPlaying){
playOnReady();
isPlaying = true;
btn.setBackgroundResource(R.drawable.durdur);
}
else{
mediaPlayer.reset();
isPlaying = false;
btn.setBackgroundResource(R.drawable.oynat);
}
}
});
This part of code belongs to the function playOnReady()
private void playOnReady(){
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}

Take a look at the Android Activity lifecycle flowchart: https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You need to account for the path where onPause is called when you leave the Activity and then onResume is called when you enter it again. The solution for you could be as simple as moving some/all of your code from onCreate into onResume.

Using this tutorial I have managed to build a service which handles the mediaplayer that I can have the control of anytime I need.

Related

Save state of MediaPlayer on rotation

I am working on an app that has included an radio and everything is fine the play, stop, and pause buttons. My problem is that whenever a song is playing and I press the back button and reopen the app the buttons won't work with the current streaming radio
This happens as well when I change the orientation. Is there a way I can save the state of the media player and then obtain the state so that I can stop the song that is being played?
public class radioActivity extends AppCompatActivity {
Button b1;
private Button Button1;
private Button Button2;
private String STREAM_URL = "http://192.99.35.93:6370/;stream.mp3";
private MediaPlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radio);
Button button1 = (Button) findViewById(R.id.buttonpredica1);
Button button2 = (Button) findViewById(R.id.buttonpredica2);
mPlayer = new MediaPlayer();
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
WifiManager.WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wifiLock.acquire();
wifiLock.release();
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mPlayer) {
mPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
This happens because every time you either press back or rotate your device, your activity is destroyed and with it goes all of its state. If you want your app to keep playing under such circumstances (which makes total sense for a radio app), you'll need to implement the media playback logic in a service:
https://developer.android.com/guide/components/services.html
Regarding your need to deal with media playback in background, there is a very complete official documentation page on this topic:
https://developer.android.com/guide/topics/media/mediaplayer.html
Create a new object or class that is not GUI related that handles the radio.
in the constructor of your GUI add a parameter MediaPlayer that then sets the respective field to the Media Player.
Adjust the code of the buttons to interact with the Media Player Field.
This will allow for you to open/close various windows that interact with the same MediaPlayer.
public radioactivity(MediaPlayer mPlayer) {
this.mPlayer = mPlayer;
}

How to release media player while preparing

I am working on music player app where I am doing streaming of music using MediaPlayer. Streaming is working fine but now I want If user press back button of the activity then it should stop preparing & release media player immediately.
Currently when it is preparing and if activity is being destroyed then I am releasing the MediaPlayer like this but when it release it then it hangs the application & show ANR.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer!=null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
I am initializing MediaPlayer like below
mediaPlayer = null;
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource("http://www.samisite.com/sound/cropShadesofGrayMonkees.mp3");
Now I want when it start preparing then on back press when I am releasing in onDestory then it should not hang the app & release the media player smoothly.
Please help me what is the best way to do this. Thanks in advance
mediaPlayer.prepareAsync();
Check the answer here. And the MediaPlayer State Diagram from android code.
Edit:
#TGMCians I showed him the provided link, So, if the playback is still not ready or preparing, he can not call stop() until it's called onPrepared. I'm not sure that onPrepared keep called after the app onDestroy called. So, The full snip I think is:
private boolean mPrepared = false;
private boolean mCancel = false;
public void onPrepared(MediaPlayer player){
mPrepared = true;
if(mCancel){
player.release();
mPrepared = false;
mCancel = false;
//nullify your MediaPlayer reference
mediaPlayer = null;
}
}
private void cancelMedia(){
mCancel = true;
}
#Override
protected void onDestroy() {
super.onDestroy();
cancelMedia();
if (mediaPlayer != null && mPrepared) {
mediaPlayer.stop();
mediaPlayer.release();
mPrepared = false;
mediaPlayer = null;
}
}

Trying to use the same button to play+pause music

I have recently tried to create a button that says "Play", and when this button is pressed, I wanted it to play the music then change the text to "Stop", but it throws an error and quits the app. Here is my code:
mPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
ourMusic.start();
mDisplay.setText("Stop");
}
}
});
So if you press the button once it should play, press it again it should stop the music. There is no errors in the actual coding.
Here is my logcat: http://pastie.org/7970711
I am new to this stuff, so I don't know too much of whats going on. Any help would be appreciated.
Use this instead:
#Override
public void onClick(View v) {
if (ourMusic == null) {
ourMusic = MediaPlayer.create(MainActivity.this, R.raw.killthenoise);
}
if(ourMusic.isPlaying()){
ourMusic.pause();
mDisplay.setText("Play");
}else{
ourMusic.start();
mDisplay.setText("Stop");
}
}
Basically don't:
Recreate ourMusic everytime there is a click to play
Try to use ourMusic when it isn't instantiated.
Add a global variable boolean flag=false;
if(flag==false)
{
mp=MediaPlayer.create(this, R.raw.abc);
mp.start();
playbutton.setText("Pause");
flag=true;
}
else if(mp.isPlaying()&&flag==true)
{
mp.pause();
playbutton.setText("Play");
flag=false;
}
This code will work if you want to use the same button as PLAY/PAUSE in your app.
Hope this helps.

Sound comes from the app when it is paused

I have problems with my app because multimedia sound is heard when the app is in background
I have defined my Media player like this;
private void playLocalAudio(int R1)throws Exception
{
MediaPlayer mediaPlayer = MediaPlayer.create(this,R1);
mediaPlayer.start();
}
For calling PlayLocalAudio I do:
try{
playLocalAudio(R.raw.fartw1);
}
catch (Exception e) {
e.printStackTrace();
}
}});
But I am not able to call correctly MediaPlayer.Stop()
I am trying:
public void onPause()
{
super.onPause();
mediaplayer.stop();
}
But it doesn't work. Could you help me?
I'm guessing that your code has a class variable mediaPlayer that's not visible in your example. In that case you have variable shadowing, because you're instantiating a new mediaPlayer in playLocalAudio and that instance is not visible inside the pause method. So stop is never called. Remove the MediaPlayer class name from the declaration in playLocalAudio.

Mediaplayer stop is not working

I have got a MediaPlayer object as class attribute.
MediaPlayer mp;
Then I use them in my onCreate method -
mp = MediaPlayer.create(getApplicationContext(), R.raw.num1);
mp.start();
Then I try to stop it from one of my buttons clicklistener like this -
btnBack = (Button) findViewById(R.id.btn1);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopSound();
startActivity(new Intent(Five.this, Four.class));
finish();
}
});
}
public void stopSound(){
if (mp != null) {
mp.release();
mp.stop();
}
}
but the stop does not work.
What am i doing wrong?
You've already released the MediaPlayer instance. It's gone. You can't call stop() on it after you release it. If you plan to resume the sound, just remove the release() call. If you want to destroy the MediaPlayer (e.g. create a new one later with MediaPlayer.create()), remove the stop() call. You should read over this documentation pretty thoroughly; the MediaPlayer class is pretty complex. You need to understand the different states and when you can and cannot call certain methods.
In some android versions, just some ones, i had a similar issue in one app streamming radio, it worked it with:
try{
if(mp!=null && mp.isPlaying()){
mp.stop();
}
mp.release();
mp=null;
mp = new MediaPlayer(); //I needed this, maybe you dont hac
}catch(Exception e){
e.printStackTrace();
System.out.println("I can't believe you get here !");
}
you can't call release before stop
have a look at the lifecycle here http://developer.android.com/reference/android/media/MediaPlayer.html

Categories

Resources