简体   繁体   中英

Media Player pauses the music when the activity loses focus(when home or screen goes off)

the mediaplayer stops music when homebutton is pressed or screen goes off....I want the music to continue even if the activity loses focus....but i want the music to pause for the incoming calls and if user pauses the music....also the music should stop when the activity is closed via the back button

here's sample of my code:

package com.example.acer.aartisangrah;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ekdanta);
    tv4 = (TextView) findViewById(R.id.textView9);
    tv4.setTextSize(18);
    tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
    b9 = (Button) findViewById(R.id.b9);
    b10 = (Button) findViewById(R.id.b10);
    seek_bar = (SeekBar) findViewById(R.id.seekBar);
    seek_bar.setOnSeekBarChangeListener(this);
    seek_bar.setEnabled(false);
    but19 = (Button) findViewById(R.id.button19);
    but19.setOnClickListener(this);
    TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
}
private final PhoneStateListener mPhoneListener=new PhoneStateListener(){
    public void onCallStateChanged(int state, String incomingNumber) {
        super.onCallStateChanged(state, incomingNumber);

        // Call receive state
        if (state != TelephonyManager.CALL_STATE_IDLE) {
            if ((play!= null) && (play.isPlaying()))
            {
                play.pause();
                but19.setBackgroundResource(R.drawable.play);
            }
        }
    }
};

public void run() {
    int currentPosition = play.getCurrentPosition();
    final int total = play.getDuration();
    while (play != null && currentPosition < total) {
        try {
            Thread.sleep(1000);
            currentPosition = play.getCurrentPosition();
        } catch (InterruptedException e) {
            return;
        } catch (Exception e) {
            return;
        }
        seek_bar.setProgress(currentPosition);
    }
}
public void onClick(View v) {
    if (v.equals(but19)) {
        if (play == null) {
            play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
            seek_bar.setEnabled(true);
        }
        if (play.isPlaying()) {
            play.pause();
            but19.setBackgroundResource(R.drawable.play);
        } else {
            play.start();
            but19.setBackgroundResource(R.drawable.pause);
            seek_bar.setMax(play.getDuration());
            new Thread(this).start();
        }
    }
    play.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            play.seekTo(0);
            but19.setBackgroundResource(R.drawable.play);
        }
    });
}

@Override
protected void onPause()
{
    super.onPause();
}

@Override
protected void onDestroy()
{
    super.onDestroy();
    play.release();
}

@Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
    try{
        if(play.isPlaying()||play!=null){
            if (fromUser)
                play.seekTo(progress);
        }
        else if(play==null){
            Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
            seek_bar.setProgress(0);
        }
    }
    catch(Exception e){
        Log.e("seek bar",""+e);
        seek_bar.setEnabled(false);
    }
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onStopTrackingTouch(SeekBar seekBar) {

}

public void increase(View inc) {
    count++;
    if (count == 1) {
        tv4.setTextSize(22);
    } else if (count == 2) {
        tv4.setTextSize(30);
    } else if (count >= 3) {
        count = 3;
        tv4.setTextSize(40);
    }
}

public void decrease(View dec) {
    count--;
    if (count <= 0) {
        tv4.setTextSize(18);
        count = 0;
    }
    if (count == 1) {
        tv4.setTextSize(22);
    } else if (count == 2) {
        tv4.setTextSize(30);
    } else if (count == 3) {
        tv4.setTextSize(40);
    }
}
}

EDIT

After using this code for the activity...this activity does not get opened on some devices...the app just closes itself....Please Help!!! Other activities without this code works just fine...

First of all, you have the following code

@Override
protected void onPause()
{
    super.onPause();
    if ((play!= null) && (play.isPlaying()))
    {
        play.pause();
    }
}

onPause method is executed every time the activity goes to background (loses focus) or when it is closed by the user. So your first step would be to remove this code from the onPause method, where you deliberately call play.pause() .

You should overwrite the onBackPressed() method and do something similar to what you are doing but calling play.stop()

Check here , specifically on the Performing cleanup section where it says the following

a MediaPlayer object can consume a significant amount of system resources, so you should keep it only for as long as you need and call release() when you are done with it. It's important to call this cleanup method explicitly rather than rely on system garbage collection because it might take some time before the garbage collector reclaims the MediaPlayer

Make sure to take a look at that guide as well.

To stop pausing of music when app gets to background. Comment play.pause() as below:

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if ((play!= null) && (play.isPlaying())) 
    { 
        // play.pause(); 
    } 
} 

The playback should itself stop it on back press (I'm almost certain). Make sure you dispose off the mediaPlayer in onDestroy() .

To stop it on call receive. Instantiate the following receiver in your activity:

// Listens for phone state and pauses in an event of call
    private final PhoneStateListener mPhoneListener = new PhoneStateListener() {
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            // Call receive state
            if (state != TelephonyManager.CALL_STATE_IDLE) {
                if ((play!= null) && (play.isPlaying())) 
                { 
                    play.pause(); 
                }
            }
        }
    };

You need to register for it as (probably in onCreate() ):

// Make mTelephonyManager an instance variable
TelephonyManager mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);

Don't forget to unregister it in onDestroy() :

mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);

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