Demo link: https://github.com/miqt/GetOperator
First post the permission required, and then determine the operator based on the prefix by obtaining imsi:
if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
TelephonyManager mTelephonyMgr = (TelephonyManager)
context.getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephonyMgr != null) {
String imsi = mTelephonyMgr.getSimOperator();
if (isEmpty(imsi)) {
imsi = mTelephonyMgr.getSubscriberId();
}
if (!isEmpty(imsi)) {
if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
return carrierName = "中国移动";
} else if (imsi.startsWith("46001")) {
return carrierName = "中国联通";
} else if (imsi.startsWith("46003")) {
return carrierName = "中国电信";
}
}
}
}
However, with restrictions such as privacy compliance, the above methods are not recommended because they need to obtain imsi. Here is a method to obtain operators without obtaining imsi.
We all know that Android will load different resource folders according to different device settings. Most typically, string resources in different languages will be loaded according to the language of the system. And Android can also load different resources according to MCC and MNC. And we can take advantage of this by creating a resource folder such as values-mcc460-mnc00, and then placing different operator names in the corresponding folder.
A country code comparison table is attached:
Of course, other countries also have:
https://zh.wikipedia.org/wiki/%E7%A7%BB%E5%8A%A8%E8%AE%BE%E5%A4%87% E7%BD%91%E7%BB%9C%E4%BB%A3%E7%A0%81
The final usage method is very simple, just get the resource string, and the Android system will automatically navigate to the correct operator name.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView view = findViewById(R.id.text);
view.setText(getString(R.string.operator));
}
}