在Android中检索来电的电话号码,需要使用TelephonyManager和PhoneStateListener。以下是一个简单的示例代码:
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
public class CallReceiver extends PhoneStateListener {
private Context context;
public CallReceiver(Context context) {
this.context = context;
}
@Override
public void onCallStateChanged(int state, String phoneNumber) {
super.onCallStateChanged(state, phoneNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
// 电话进来时,phoneNumber为来电号码
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// 接听电话时,phoneNumber为对方号码
break;
case TelephonyManager.CALL_STATE_IDLE:
// 挂断电话时,phoneNumber为空
break;
}
}
}
在AndroidManifest.xml中添加以下权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
然后在需要监听来电的地方,注册CallReceiver:
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
CallReceiver callReceiver = new CallReceiver(context);
telephonyManager.listen(callReceiver, PhoneStateListener.LISTEN_CALL_STATE);
在不需要监听时,记得取消注册CallReceiver:
telephonyManager.listen(callReceiver, PhoneStateListener.LISTEN_NONE);
这样就可以在来电时获取到来电号码了。
没有搜到相关的文章