2

我正在尝试获取来电的来电号码。我在 Android 中搜索并找到了这个 Retrieve incoming call's phone number。我的问题是我无法在 4.0.3 以上的版本中“输入号码”。如果我做错了什么,或者如何在 4.0.3 以上版本中获取传入号码,请指导我。提前致谢。这是代码:

TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(new PhoneStateListener(){
   public void onCallStateChanged(int state, String incomingNumber) {
       super.onCallStateChanged(state, incomingNumber);
          switch (state) {
              // not getting incoming number in latest version of android
              Log.e(Utils.TAG, "incomingNumber: "+incomingNumber);
          }
    }
},PhoneStateListener.LISTEN_CALL_STATE);
4

2 回答 2

3

在您的清单中创建一个接收器:

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

添加此权限:

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

创建广播接收器:

public class PhoneState extends BroadcastReceiver {

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

        TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE); 

        switch (tm.getCallState()) {

            case TelephonyManager.CALL_STATE_RINGING:
                    String phoneNr= intent.getStringExtra("incoming_number");
                    Toast.makeText(context, phoneNr,Toast.LENGTH_LONG).show();
                    break;
        } 
    }
}
于 2013-11-15T16:42:55.217 回答
0

我遇到了同样的问题。使用以下代码修复:

if (ActivityCompat.checkSelfPermission(this,
    Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]
    {Manifest.permission.READ_PHONE_STATE},3);
} 
于 2017-05-26T05:39:40.180 回答