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

Ví dụ này minh họa cách kiểm tra trạng thái GPS và mở màn hình cài đặt vị trí để người dùng bật/tắt GPS (Android không cho phép app bật/tắt GPS trực tiếp vì bảo mật).

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: 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/buttonGps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Bật/Tắt GPS"/>
    <TextView
        android:id="@+id/textView"
        android:layout_centerInParent="true"
        android:layout_marginBottom="20dp"
        android:layout_above="@id/buttonGps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:text="Dịch vụ vị trí" />
</RelativeLayout>

Bước 3: Code kiểm tra và mở cài đặt (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 {
    TextView textView;
    Button buttonGps;
    Context context;
    LocationManager locationManager;
    boolean gpsStatus;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        textView = findViewById(R.id.textView);
        buttonGps = findViewById(R.id.buttonGps);
        context = getApplicationContext();
        
        checkGPSStatus();
        
        buttonGps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        });
    }

    private void checkGPSStatus() {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        gpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        
        if (gpsStatus) {
            textView.setText("Dịch vụ vị trí: ĐÃ BẬT");
        } else {
            textView.setText("Dịch vụ vị trí: ĐÃ TẮT");
        }
    }
}

Bước 4: Manifest với quyền (AndroidManifest.xml)

<?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"/>
    <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>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. App hiển thị trạng thái GPS. Nhấn nút để mở cài đặt vị trí.

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

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

Lưu ý quan trọng: Từ Android 6.0 (API 23), app không thể bật/tắt GPS trực tiếp qua code (SecurityException). Chỉ có thể dẫn user đến màn hình cài đặt bằng Settings.ACTION_LOCATION_SOURCE_SETTINGS. Từ Android 10+, có API mới LocationRequest.Builder.setLocationSettingsIgnored() nhưng vẫn cần user consent.