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

Cách bật/tắt GPS theo chương trình trong Android

Giới thiệu

Hướng dẫn này trình bày cách kiểm tra trạng thái GPS và mở cài đặt vị trí để người dùng bật/tắt GPS trong Android. Lưu ý: Không thể bật/tắt GPS trực tiếp theo chương trình do chính sách bảo mật Android (từ API 19+).

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

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:text="Mở cài đặt vị trí (Bật/Tắt GPS)" />
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="132dp"
        android:gravity="center"
        android:text="Trạng thái GPS hiển thị tại đây"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Bước 3: Viết logic xử lý (src/MainActivity.java)

import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button button;
    Context context;
    Intent intent;
    TextView textView;
    LocationManager locationManager;
    boolean gpsStatus;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        button = findViewById(R.id.button1);
        textView = findViewById(R.id.textView1);
        context = getApplicationContext();
        
        checkGpsStatus();
        
        button.setOnClickListener(v -> {
            // MỞ CÀI ĐẶT VỊ TRÍ - Người dùng tự bật/tắt
            intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        });
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // Kiểm tra lại khi quay lại từ Settings
        checkGpsStatus();
    }
    
    public void checkGpsStatus() {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        
        if (locationManager != null) {
            gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            
            if (gpsStatus) {
                textView.setText("GPS: ĐÃ BẬT ✓");
                textView.setTextColor(Color.GREEN);
            } else {
                textView.setText("GPS: ĐÃ TẮT ✗");
                textView.setTextColor(Color.RED);
            }
        }
    }
}

Bước 4: Cấu hình Manifest (androidManifest.xml) - Cần quyền

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    
    <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>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Giải thích quan trọng

Tại sao không bật/tắt GPS trực tiếp?

  • Android 4.0 (API 14) cho phép ghi Settings.Secure.LOCATION_PROVIDERS_ALLOWED
  • Từ Android 4.1 (API 16), Google khóa chặt việc này vì bảo mật/quyền riêng tư
  • Chỉ ứng dụng hệ thống (system app) hoặc có quyền đặc biệt mới được
  • Giải pháp chuẩn: Mở màn hình cài đặt vị trí (Settings.ACTION_LOCATION_SOURCE_SETTINGS)

Cách kiểm tra GPS hiện đại (API 28+)

// LocationManager deprecated một số method
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean gpsEnabled = lm.isLocationEnabled(); // API 28+
// Hoặc
boolean gpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);

Xin quyền Runtime (API 23+)

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) 
    != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        REQUEST_LOCATION_PERMISSION);
}

Chạy ứng dụng

Kết nối thiết bị Android, cấp quyền vị trí khi yêu cầu, nhấn Run trong Android Studio. Nhấn nút để mở cài đặt vị trí, bật/tắt GPS, quay lại app sẽ thấy trạng thái cập nhật.

Cách bật/tắt GPS theo chương trình trong Android

Cách bật/tắt GPS theo chương trình trong Android

Cách bật/tắt GPS theo chương trình trong Android