我正在尝试接收来电号码。我搜索并找到了这个 Retrieve incoming call's phone number in Android。 我的问题是我无法在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);
答案 0 :(得分:4)
在清单中创建一个接收器:
<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;
}
}
}
答案 1 :(得分:0)
我遇到了同样的问题。 修复了以下代码:
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.READ_PHONE_STATE},3);
}