在Call End Broadcast Receiver中获取电话号码?

时间:2014-08-10 20:07:35

标签: android android-intent broadcastreceiver

我正在开发一个一个接一个地进行一系列调用的应用程序。为了检测呼叫是否已经结束,我创建了广播接收器,当呼叫结束时成功触发,但我无法获得其中的电话号码。这是我的代码

public class EndCallReceiver extends BroadcastReceiver {

Preferences pref;
Context ctx;

@Override
public void onReceive(Context context, Intent intent) {

    ctx = context;
    pref = new Preferences(ctx);

    Bundle extras = intent.getExtras();
    if (extras != null) {
        String state = extras.getString(TelephonyManager.EXTRA_STATE);
        String incomingNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);


        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
            Toast.makeText( ctx, incomingNumber, Toast.LENGTH_LONG).show();
        }


      }
  }

}

Toast中没有显示任何内容。 incomingNumber为null。有谁能告诉我。如何在终端呼叫BroadcastReceiver中获取电话号码。

2 个答案:

答案 0 :(得分:1)

在AndroidManifest.xml中,您需要注册广播:

<receiver android:name=".EndCallReceiver" >
   <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE" />
   </intent-filter>
</receiver>

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

您的代码:

public class EndCallReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

     Bundle bundle = intent.getExtras();
     String phoneNumber= bundle.getString("incoming_number");        
  }

}

答案 1 :(得分:1)

问题在于,当调用以下内容时,没有关联的电话号码。

if (state.equals(TelephonyManager.EXTRA_STATE_IDLE))

请尝试以下代码:

当电话响铃时,电话号码会被保存,以及稍后通话时 断开连接,然后显示前一个号码。

public class CallReceiver extends BroadcastReceiver {

static boolean isRinging = false;
String number = "";

@Override
public void onReceive(Context context, Intent intent) {
    Log.v("ranjith", "entered onregister");
    // Get the current Phone State
    String phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if (phoneState == null)
        return;

    // If phone is "Ringing"
    if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        isRinging = true;
        number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.v("ranjith", "phone ringing");
    }

    // if phone is idle after ringing
    if (phoneState.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
        Log.v("ranjith", "call ended of number" + number);
        Toast.makeText(context, "Number is " + number, Toast.LENGTH_LONG).show();
    }
}
}