当活动失去焦点时(主页或屏幕熄灭时),媒体播放器会暂停音乐

时间:2016-08-09 17:36:10

标签: java android android-mediaplayer

当按下主页按钮或屏幕熄灭时,媒体播放器会停止音乐....即使活动失去焦点,我也希望音乐继续播放....但我希望音乐暂停以接听来电以及用户是否暂停音乐......当通过后退按钮关闭活动时音乐应该停止

这是我的代码示例:

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);
    }
}
}

编辑

使用此代码进行活动后...此活动无法在某些设备上打开...应用程序只是自行关闭....请帮助! 没有此代码的其他活动也可以正常工作......

2 个答案:

答案 0 :(得分:5)

首先,您有以下代码

@Override
protected void onPause()
{
    super.onPause();
    if ((play!= null) && (play.isPlaying()))
    {
        play.pause();
    }
}
每次活动进入后台(失去焦点)或用户关闭时,都会执行

onPause方法。因此,您的第一步是从onPause方法中删除此代码,您可以在其中故意调用play.pause()

您应该覆盖onBackPressed()方法并执行类似于您正在执行的操作,但调用play.stop()

检查here,特别是执行清理部分,其中显示以下内容

  

MediaPlayer对象可能占用大量系统   资源,所以你应该只保留它,只要你需要和打电话   完成后释放()。这称之为重要   显式清理方法而不是依赖系统垃圾   收集因为垃圾可能需要一些时间   收集器收回MediaPlayer

请务必查看该指南。

答案 1 :(得分:3)

当应用到达后台时停止播放音乐。评论play.pause()如下:

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

播放本身应该在后退时停止播放(我几乎可以肯定)。确保在onDestroy()

中丢弃mediaPlayer

在通话接收时停止。在您的活动中实例化以下接收者:

// 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(); 
                }
            }
        }
    };

您需要注册(可能在onCreate()):

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

请勿忘记在onDestroy()中取消注册:

mTelephonyManager.listen(mPhoneListener, PhoneStateListener.LISTEN_NONE);