1. 获取TelephonyManager实例:
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
2. 获取设备的电话状态:
int callState = telephonyManager.getCallState();
// 返回值可能是:TelephonyManager.CALL_STATE_IDLE, TelephonyManager.CALL_STATE_RINGING, TelephonyManager.CALL_STATE_OFFHOOK
3. 获取设备的电话号码:
String phoneNumber = telephonyManager.getLine1Number();
4. 获取设备的IMEI号(设备唯一标识码):
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
String imei = telephonyManager.getDeviceId();
} else {
// 请求权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
}
5. 获取SIM卡相关信息:
String simOperator = telephonyManager.getSimOperator();
String simOperatorName = telephonyManager.getSimOperatorName();
String simSerialNumber = telephonyManager.getSimSerialNumber();
6. 监听电话状态变化:
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String phoneNumber) {
super.onCallStateChanged(state, phoneNumber);
// 处理电话状态变化
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
请注意,为了使用某些功能,你可能需要在AndroidManifest.xml中添加相应的权限,比如读取电话状态的权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
此外,要确保在运行时请求必要的权限,以避免在运行时出现权限问题。
转载请注明出处:http://www.zyzy.cn/article/detail/15242/Android