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

Cách lấy thông tin thành phố từ Network Provider Android

Giới thiệu

Hướng dẫn này trình bày cách lấy thông tin thành phố (city) của vị trí hiện tại sử dụng Network Provider (mạng di động/WiFi) 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);
        
        // Kiểm tra và yêu cầu quyền vị trí
        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;
        }

        // Lấy vị trí cuối cùng từ Network Provider
        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) {
                updateCityName();
            }
        }
    }

    @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) {
            updateCityName();
        }
    }

    private void updateCityName() {
        if (location == null) {
            textView.setText("Không lấy được vị trí");
            return;
        }
        
        try {
            List
addresses = geocoder.getFromLocation( location.getLatitude(), location.getLongitude(), 1); if (addresses != null && !addresses.isEmpty()) { Address address = addresses.get(0); String city = address.getLocality(); textView.setText(city != null ? city : "Không xác định"); } else { textView.setText("Không tìm thấy địa chỉ"); } } catch (IOException e) { e.printStackTrace(); textView.setText("Lỗi: " + 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 chi tiết

Network Provider vs GPS Provider

Đặc điểmNETWORK_PROVIDERGPS_PROVIDER
Độ chính xác~100-1000m (trạm phát/WiFi)~5-50m (GPS vệ tinh)
Tốc độ lấy vị tríNhanh (giây)Chậm (phút)
Tiêu tốn pinThấpCao
Hoạt động trong nhàTốtKém
Yêu cầu quyềnACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION

Các thông tin có thể lấy từ Address

address.getLocality()        // Thành phố/Quận (City)
address.getSubLocality()     // Phường/Xã (Ward/Commune)
address.getAdminArea()       // Tỉnh/Thành phố trực thuộc TW (State/Province)
address.getCountryName()     // Tên quốc gia
address.getCountryCode()     // Mã quốc gia (VN, US, JP...)
address.getPostalCode()      // Mã bưu chính
address.getThoroughfare()    // Tên đường
address.getSubThoroughfare() // Số nhà

Lưu ý quan trọng

  • Geocoder cần kết nối Internet để hoạt động (gọi API Google).
  • Sử dụng Locale.getDefault() để kết quả tiếng Việt.
  • Xử lý null cho location (chưa có vị trí last known).
  • Từ Android 10+, cần quyền ACCESS_BACKGROUND_LOCATION để lấy vị trí nền.
  • Cân nhắc dùng FusedLocationProviderClient (Google Play Services) cho chính xác hơn.