如何在广播接收器呼叫号码或OFFHOOK状态时启动音频歌曲,并在IDLE或呼叫结束时停止播放。
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();
}
}
}
}
答案 0 :(得分:0)
声明类变量,如下面的broadcastreceiver代码中所示:
public class PhonecallReceiver extends BroadcastReceiver {
static String phoneNumber;
private static boolean ringing, received;
.......................
接下来在onReceive方法中输入以下代码:
收到电话号码时,状态为: 的 IDLE> RINGING> OFFHOOK> IDLE 强>
如果未收到电话号码,则状态为: 的 IDLE> RINGING> IDLE 强>
当状态为RINGING时,将振铃变量设置为true,然后当状态为OFFHOOK时,检查变量振铃是否为真,然后选择呼叫并启动音频并将振铃设置为false并接收为true。 接下来,当状态为IDLE时,检查收到的变量是否为真,然后选择的呼叫被断开,现在开始播放音乐。
@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;
}
}