当广播接收器 call 一个号码或状态为OFFHOOK时如何启动音频歌曲,以及在IDLE或 call 结束时如何停止音频歌曲。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import android.media.MediaPlayer;
public class Ringing extends BroadcastReceiver{
Context context;
public static MediaPlayer ob=null;
@Override
public void onReceive(Context context, Intent intent){
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
// Toast.makeText(context, "Call Recieved", Toast.LENGTH_LONG).show();
ob = MediaPlayer.create(context,R.raw.trouble);
ob.start();
}
if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
if(ob.isPlaying()) {
ob.stop();
ob.destroy();
}
}
}
}
最佳答案
声明类变量,如下面的broadcastreceiver代码所示:
public class PhonecallReceiver extends BroadcastReceiver {
static String phoneNumber;
private static boolean ringing, received;
.......................
接下来,在onReceive方法中放入以下代码:
收到电话号码后,状态为:
IDLE>铃声> OFFHOOK> IDLE
未收到电话号码时,状态为:
IDLE> RINGING> IDLE
当状态为RINGING时,将振铃变量设置为true,然后在状态为OFFHOOK时检查变量振铃是否为true,然后接听电话并启动音频,还将振铃设置为false并接收为true。
接下来,当状态为“空闲”时,检查接收到的变量是否为true,然后断开所选择的 call ,现在开始播放音乐。
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
String state = bundle.getString(TelephonyManager.EXTRA_STATE);
String temp = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
if (!(state == null) && state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
ringing = true;
received = false;
} else if (!(state == null) && state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK) && ringing) {
received = true;
ringing = false;
//add code to start music
} else if (!(state == null) && state.equals(TelephonyManager.EXTRA_STATE_IDLE) && received) {
//add code to stop music
received = false;
ringing = false;
}
}
关于android - 如何在广播接收器处于摘机状态时启动音频歌曲,以及如何在拨盘关闭时停止音频歌曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30154141/