问题
I am trying to fetch incoming number of incoming call. I searched and found this Retrieve incoming call's phone number in Android. My issue is that I am not able to "incoming number" in version above 4.0.3. Please guide me if I am doing anything wrong ,or how to get the incoming number in version above 4.0.3. Thanks in advance. Here is code :
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);
回答1:
Create a receiver in your manifest:
<receiver android:name=".PhoneState">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
add this permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
create the broadcast receiver:
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;
}
}
}
回答2:
I run into the same issue. Fixed with following code:
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE)!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.READ_PHONE_STATE},3);
}
来源:https://stackoverflow.com/questions/19005642/get-phone-number-of-incoming-call-in-all-android-versions