Get phone number of incoming call in all android versions

我只是一个虾纸丫 提交于 2019-12-11 02:41:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!