gpt4 book ai didi

java - 如何防止我的音乐播放器在我的电话响起并挂断后启动?

转载 作者:搜寻专家 更新时间:2023-11-01 09:37:41 24 4
gpt4 key购买 nike

此代码有效。我遇到的唯一问题是,当我不使用该应用程序时,电话响了,挂断电话后音乐还在播放。

public void level_one(View view){

mp3 = MediaPlayer.create(this, R.raw.alpha_12);

PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
mp3.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
mp3.start(); // Runs this line even if I didn't play
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
mp3.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}

最佳答案

只需引入一个 boolean 值即可跟踪之前是否播放过音乐。我刚刚组成了你周围的类(class),但你明白了。

public class MyClass
{
private boolean isMusicPlaying = false;

public void someFunctionWhichStartsMusic()
{
//start the music

isMusicPlaying = true;
}

public void level_one(View view){

mp3 = MediaPlayer.create(this, R.raw.alpha_12);

PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING)
{
mp3.pause();
}
else if(state == TelephonyManager.CALL_STATE_IDLE
&& isMusicPlaying) // pay attention to this!
{
mp3.start();
}
else if(state == TelephonyManager.CALL_STATE_OFFHOOK)
{
mp3.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
}

关于java - 如何防止我的音乐播放器在我的电话响起并挂断后启动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41811385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com