使用Telephony Manager为手机号码返回空值,我想直接将手机号码输入应用程序而不询问用户。
答案 0 :(得分:0)
您可以使用TelephonyManager
执行此操作:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tm.getLine1Number();
如果号码“不可用”,getLine1Number()
将返回null
,但不会说明号码何时可用。
您需要通过在Manifest中添加以下内容来授予您的应用程序进行此查询的权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
答案 1 :(得分:0)
尝试使用以下给定的方法生成国家/地区代码
private void getCountryCode() {
int code = 0;
TelephonyManager telephonyManager = (TelephonyManager) getActivity().
getSystemService(Context.TELEPHONY_SERVICE);
String CountryISO = telephonyManager.getSimCountryIso().toString().toUpperCase();
;
//String NetworkCountryIso = telephonyManager.getNetworkCountryIso().toString();
String number = telephonyManager.getLine1Number();
code = getCountryCodeForRegion(CountryISO);
Log.i("CountryISO", "CountryISO " + CountryISO);
Log.i("code", "code " + code);
Log.i("number ", "number " + number);
}
从regionCode
获取CountryCodepublic int getCountryCodeForRegion(String regionCode) {
int result = -1;
try {
Class c = Class.forName("com.android.i18n.phonenumbers.PhoneNumberUtil");
Method getInstance = c.getDeclaredMethod("getInstance");
Method getCountryCodeForRegion = c.getDeclaredMethod("getCountryCodeForRegion", String.class);
Object instance = getInstance.invoke(null);
Integer code = (Integer) getCountryCodeForRegion.invoke(instance, regionCode);
result = code;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} finally {
return result;
}
}
不要忘记在AndroidManifest中添加权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>