5

我收到来电详细信息(Number,Name,Date)。但是如何获取拨出电话的详细信息。我已经为拨出电话详细信息编写了代码,但它会抛出NullPointerException. 下面是我的MyCallReceiver.java 文件和清单文件

  public void onReceive(Context context, Intent intent) {

    this.context = context;



    if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {

        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

        Toast.makeText(context, "Call From : " + incomingNumber, Toast.LENGTH_LONG).show();

        doToast(getContactName(context, incomingNumber) + " " + incomingNumber);
        String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
        doToast(currentDateTimeString +" "+incomingNumber);


    } else if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE) || intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
        Toast.makeText(context, "DETECTED CALL HANG UP EVENT", Toast.LENGTH_LONG).show();

        String outgoingNumber=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Toast.makeText(context,"Calling To :"+outgoingNumber,Toast.LENGTH_LONG).show();
    }
 }
4

3 回答 3

4
public void onReceive(Context context, Intent intent)
{
    String state=intent.getStringExtra(TelephonyManager.EXTRA_STATE);

    if(state==null)
    {
        //Outgoing call
        String number=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        Log.i("tag","Outgoing number : "+number);
    }
    else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING))
    {
        //Incoming call
        String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.i("tag","Incoming number : "+number);
    }
}
于 2015-09-22T13:19:31.850 回答
1

首先,intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER) 在电话状态空闲时为您提供拨出号码,并在电话状态更改为 OFF_HOOK 时变为“null”。

最简单的方法是在另一个 onRecive 发生之前保存该号码。

于 2015-09-22T12:42:51.627 回答
0

为不同的事件(即来电和去电)创建单独的侦听器可能会让您的生活更轻松。对于拨出电话,您可能需要创建一个IntentFilter.

IntentFilter filterCalls = new IntentFilter();
filterCalls.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
MyCallReceiver myCallReceiver = new MyCallReceiver();
registerReceiver(myCallReceiver, filterCalls);

然后在你的onReceive你可以简单地拥有:

 String outgoingNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER)

并确保它会起作用。

于 2015-09-22T13:01:43.677 回答