【问题标题】:How to start a audio song when the Broadcast Receiver gets the state of offhook and stop it when the dial closes如何在广播接收器处于摘机状态时开始播放音频歌曲并在拨号盘关闭时停止播放
【发布时间】:2015-05-10 17:02:10
【问题描述】:

如何在广播接收器呼叫一个号码或处于 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();
           }
        }
    }
}

【问题讨论】:

  • 您当前的代码有什么问题?
  • 我想知道收件人何时拨打电话

标签: android audio broadcastreceiver telephonymanager android-dialer


【解决方案1】:

在广播接收器代码中声明类变量如下所示:

public class PhonecallReceiver extends BroadcastReceiver {
    static String phoneNumber;
    private static boolean ringing, received;
    .......................

接下来在 onReceive 方法中输入以下代码:

收到电话号码后,状态为: 空闲>振铃>摘机>空闲

当未收到电话号码时,状态为: 空闲>振铃>空闲

当状态为 RINGING 时,将振铃变量设置为 true,然后当状态为 OFFHOOK 时,检查变量振铃是否为 true,然后选择呼叫并开始音频,并将振铃设置为 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;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-03
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    相关资源
    最近更新 更多