Get incoming call number programmatically on android

偶尔善良 提交于 2021-02-08 08:06:34

问题


I am trying to get incoming call info using broadcast receivers on android studio. following are the methods i tried:

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

On this receiver's intent i tried:

Method one:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

Method two:

final String state1 = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        telephony.listen(new PhoneStateListener(){
            @Override
            public void onCallStateChanged(int state, final String incomingNumber) {
                super.onCallStateChanged(state, incomingNumber);
                incnumber=incomingNumber;
            }
        },PhoneStateListener.LISTEN_CALL_STATE);

Method Three:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

All the three methods return empty incnumber.

By the way, I am running this project on android pie, Please help me out.


回答1:


Try this way... permission

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

Make a Broadcast receiver say ServiceReceiver assign its action in Manifest.

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

ServiceReceiver.Java

public class ServiceReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, Intent intent) {
    TelephonyManager telephony = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
    telephony.listen(new PhoneStateListener(){
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            System.out.println("incomingNumber : "+incomingNumber);
        }
    },PhoneStateListener.LISTEN_CALL_STATE);
}

}



来源:https://stackoverflow.com/questions/54938774/get-incoming-call-number-programmatically-on-android

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