因为手头一个项目,需要读取用户手机号,结合在网上搜索的,整理了一下,方便下次使用,本次测试用的是三星手机+联通手机卡,能正常取到手机号,不过前面有+86,处理一下就OK了。
下面是代码:
package com.example.httpqingqiu.Tools;
import android.content.*;
import android.telephony.TelephonyManager;
public class PhoneHelper {
private Context context;
private TelephonyManager telephonyManager;
public PhoneHelper(Context context){
this.context=context;
telephonyManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
}
/**
* 从 SIM卡中取手机号
* @return
*/
public String GetMobileNum(){
String NativePhoneNumber=null;
NativePhoneNumber=telephonyManager.getLine1Number();
if(NativePhoneNumber!=null && NativePhoneNumber.length()>1){
String fstr=NativePhoneNumber.substring(0, 3);
if(fstr.equals("+86")){
NativePhoneNumber=NativePhoneNumber.substring(3);
}
}
return NativePhoneNumber;
}
/**
* 取电话服务商
* @return
*/
public String getProvidersName() {
String ProvidersName = null;
// 返回唯一的用户ID;就是这张卡的编号神马的
String IMSI = telephonyManager.getSubscriberId();
// IMSI号前面3位460是国家,紧接着后面2位00 02是中国移动,01是中国联通,03是中国电信。
System.out.println(IMSI);
if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
ProvidersName = "中国移动";
} else if (IMSI.startsWith("46001")) {
ProvidersName = "中国联通";
} else if (IMSI.startsWith("46003")) {
ProvidersName = "中国电信";
}
return ProvidersName;
}
}