我正在尝试在代码收到来电时播放音频文件。问题是 当收到来电时,音频文件开始播放两次或与语音重叠。另一个问题是结束通话后,音频文件不会暂停或停止,它将继续播放,直到音频文件未结束。 我为此尝试的代码如下:
public void onReceive(final Context context, Intent intent) {
try{
final MediaPlayer mp= MediaPlayer.create(context,R.raw.audio);
String state= intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context, "Ringing!", Toast.LENGTH_SHORT).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent1 = new Intent(context, AcceptCall.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent1);
mp.setLooping(false);
mp.start();
}
}, 4000);
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_OFFHOOK)){
Toast.makeText(context, "Received!", Toast.LENGTH_SHORT).show();
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)){
try{
mp.reset();
mp.pause();
mp.seekTo(0);
Toast.makeText(context, "Idle!", Toast.LENGTH_SHORT).show();
}catch(Exception e){e.printStackTrace();}
}
}catch (Exception e){
e.printStackTrace();
}
}
帮帮我摆脱困境
首先,您不会发布与之前创建的相同的MediaPlayer
实例。
每次调用MediaPlayer.create(context,R.raw.audio);
都会创建一个新的MediaPlayer
实例。因此,实际上,第一次收到广播MP_1
EXTRA_STATE_RINGING
当您收到EXTRA_STATE_IDLE
创建新MP_2
并停止/释放该实例时,您第二次开始。而是将媒体播放器引用保留在BroadCast
类中,并且仅在TelephonyManager.EXTRA_STATE_RINGING
中创建一个。这样:
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_RINGING)){
Toast.makeText(context, "Ringing!", Toast.LENGTH_SHORT).show();
mp= MediaPlayer.create(context,R.raw.audio);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent1 = new Intent(context, AcceptCall.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
| Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent1);
mp.setLooping(false);
mp.start();
}
}, 4000);
}
if(state.equalsIgnoreCase(TelephonyManager.EXTRA_STATE_IDLE)){
try{
mp.stop();
mp.release();
Toast.makeText(context, "Idle!", Toast.LENGTH_SHORT).show();
}catch(Exception e){e.printStackTrace();}
}
所以后来当你在TelephonyManager.EXTRA_STATE_IDLE
释放它时,你释放并停止同一个。
另请注意,我还替换了mp.reset()...
.