Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách lấy mã quốc gia hiện tại từ Network Provider Android

Giới thiệu

Hướng dẫn này trình bày cách lấy mã quốc gia (country code - ISO 3166-1 alpha-2) của vị trí hiện tại sử dụng Network Provider và Geocoder trên Android.

Các bước thực hiện

Bước 1: Tạo dự án mới

Tạo dự án Android Studio: File → New Project.

Bước 2: Layout activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:textSize="30sp"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Bước 3: MainActivity.java

package com.example.myapplication;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    Location location;
    Geocoder geocoder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);

        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED 
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, 
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 101);
            return;
        }

        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        geocoder = new Geocoder(this, Locale.getDefault());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 101) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                updateCountryCode();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
                == PackageManager.PERMISSION_GRANTED 
                || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
                == PackageManager.PERMISSION_GRANTED) {
            updateCountryCode();
        }
    }

    private void updateCountryCode() {
        if (location == null) {
            textView.setText("Không lấy được vị trí từ Network Provider");
            return;
        }
        
        try {
            List
addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1); if (addresses != null && !addresses.isEmpty()) { Address address = addresses.get(0); String countryCode = address.getCountryCode(); textView.setText("Mã quốc gia: " + (countryCode != null ? countryCode : "Không xác định")); } else { textView.setText("Không tìm thấy địa chỉ từ vị trí này"); } } catch (IOException e) { e.printStackTrace(); textView.setText("Lỗi Geocoder: " + e.getMessage()); } } }

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                

Giải thích Country Code (ISO 3166-1 alpha-2)

Định dạng

Mã quốc gia gồm 2 chữ cái in hoa theo chuẩn ISO 3166-1 alpha-2.

Ví dụ phổ biến

Quốc giaMã (Country Code)Tên tiếng ViệtTên tiếng Anh
Việt NamVNViệt NamVietnam
Hoa KỳUSHoa KỳUnited States
Nhật BảnJPNhật BảnJapan
Hàn QuốcKRHàn QuốcSouth Korea
Trung QuốcCNTrung QuốcChina
SingaporeSGSingaporeSingapore
MalaysiaMYMalaysiaMalaysia
Thái LanTHThái LanThailand
ĐứcDEĐứcGermany
PhápFRPhápFrance

Phân biệt các loại "Mã quốc gia"

Loại mãChuẩnVí dụ VNNguồn
Country Code (ISO 3166-1 alpha-2)ISO 3166VNGeocoder.getCountryCode()
Country Code (ISO 3166-1 alpha-3)ISO 3166VNMAddress.getCountryCode() 3 chữ cái (ít dùng)
MCC (Mobile Country Code)ITU E.212452TelephonyManager.getNetworkOperator() (3 số đầu)
MNC (Mobile Network Code)ITU E.21202 (Viettel), 01 (Vinaphone)TelephonyManager.getNetworkOperator() (3 số sau)
Region Code (Locale)ISO 3166 + ISO 639vi_VN, vi_VN@calendar=gregorianLocale.getDefault().getCountry()
Calling CodeITU-T E.164+84TelephonyManager.getNetworkCountryIso() (đôi khi)

Lấy MCC/MNC từ SIM (Khác với Geocoder)

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) 
        == PackageManager.PERMISSION_GRANTED) {
    String networkOperator = telephonyManager.getNetworkOperator(); // Ví dụ: "45202"
    if (networkOperator != null && networkOperator.length() >= 3) {
        String mcc = networkOperator.substring(0, 3); // "452" - Việt Nam
        String mnc = networkOperator.substring(3);    // "02" - Viettel
    }
}

Lưu ý quan trọng

  • Geocoder cần Internet, dựa trên dữ liệu Google Maps.
  • Network Provider độ chính xác ~100m-1km - có thể sai quốc gia ở vùng biên giới.
  • getCountryCode() trả về null nếu không xác định được.
  • Sử dụng Locale.getDefault() cho Geocoder để tên quốc gia theo ngôn ngữ thiết bị.
  • MCC/MNC từ SIM phản hồi nhà mạng thực tế, không phụ thuộc vị trí GPS.