在Android

时间:2019-03-01 06:00:03

标签: android broadcastreceiver telephonymanager

我正在尝试使用android studio上的广播接收器获取来电信息。 以下是我尝试过的方法:

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

我尝试了此接收者的意图:

方法一:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

方法二:

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);

方法三:

incnumber=intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);

这三种方法都返回空的incnumber。

顺便说一句,我正在android pie上运行此项目,请帮帮我。

1 个答案:

答案 0 :(得分:0)

尝试一下... 权限

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

让广播接收者说ServiceReceiver在清单中分配其动作。

<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);
}

}