การตรวจสอบและเปิด/ปิด GPS (Location) โดยโปรแกรมใน Android
ตัวอย่างนี้สาธิตวิธีตรวจสอบสถานะ GPS และเปิดหน้าตั้งค่า Location ให้ผู้ใช้เปิด/ปิดด้วยตนเอง (Android ไม่อนุญาตให้แอปเปิด/ปิด GPS โดยตรงแล้ว)
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่
เปิด Android Studio เลือก File → New Project และกรอกข้อมูลที่จำเป็น
ขั้นตอนที่ 2: จัดทำ Layout (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="เปิดการตั้งค่า 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="สถานะ GPS จะแสดงที่นี่"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
ขั้นตอนที่ 3: เขียนโค้ดหลัก (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(new View.OnClickListener() {
@Override
public void onClick(View v) {
// เปิดหน้าตั้งค่า Location (ผู้ใช้ต้องกดเปิด/ปิดเอง)
intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
// ตรวจสอบสถานะใหม่เมื่อกลับมาจากหน้าตั้งค่า
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: เปิดใช้งาน ✅");
textView.setTextColor(0xFF4CAF50); // สีเขียว
} else {
textView.setText("GPS: ปิดใช้งาน ❌");
textView.setTextColor(0xFFF44336); // สีแดง
}
}
}
}
ขั้นตอนที่ 4: กำหนด Permission ใน 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" />
<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>
การทดสอบ
รันแอปพลิเคชัน จะแสดงสถานะ GPS กดปุ่ม "เปิดการตั้งค่า GPS" จะไปที่หน้าตั้งค่า Location ลองสลับ GPS แล้วกลับมาแอป สถานะจะอัปเดต



⚠️ ข้อสำคัญ: Android ไม่อนุญาตให้แอปเปิด/ปิด GPS โดยตรง
ตั้งแต่ Android 4.0+ (API 14) ระบบ บล็อกการเปลี่ยนแปลง GPS ผ่านโค้ดโดยตรง (Security Policy) วิธีเดียวคือนำผู้ใช้ไปหน้าตั้งค่า:
// วิธีที่ถูกต้อง Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); // วิธีที่ใช้ไม่ได้ (จะโยน SecurityException) // locationManager.setProviderEnabled(LocationManager.GPS_PROVIDER, true); // ❌
Location Providers
| Provider | คำอธิบาย | ความแม่นยำ | พลังงาน |
|---|---|---|---|
GPS_PROVIDER |
GPS ดาวเทียม | สูงมาก (~10ม.) | สูง |
NETWORK_PROVIDER |
Wi-Fi + Mobile Network | ปานกลาง (~100-1000ม.) | ต่ำ |
PASSIVE_PROVIDER |
รับจากแอปอื่นที่ขอ Location | ขึ้นอยู่กับแอปอื่น | ต่ำมาก |
FUSED_PROVIDER |
Google Play Services (แนะนำ) | สูง + ประหยัดแบต | ต่ำ |
แนวทางปฏิบัติที่ดีที่สุด (Modern Approach)
ใช้ FusedLocationProviderClient จาก Google Play Services:
// build.gradle
implementation 'com.google.android.gms:play-services-location:21.0.1'
// ใน Activity
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// ขอ Location ครั้งเดียว
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, location -> {
if (location != null) {
// ใช้ location.getLatitude(), location.getLongitude()
}
});
}
// ตรวจสอบ Location Settings (เปิด GPS อัตโนมัติผ่าน Dialog)
LocationRequest locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, response -> {
// GPS พร้อมใช้งาน
});
task.addOnFailureListener(this, e -> {
if (e instanceof ResolvableApiException) {
// แสดง Dialog ให้ผู้ใช้เปิด GPS
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Handle error
}
}
});
Permission สำหรับ Android 10+ (API 29+)
ACCESS_FINE_LOCATION- ตำแหน่งแม่นยำ (GPS)ACCESS_COARSE_LOCATION- ตำแหน่งประมาณ (Network)ACCESS_BACKGROUND_LOCATION- ตำแหน่งในพื้นหลัง (ต้องขอแยกต่างหาก)
ต้องขอ Runtime Permission (requestPermissions) ก่อนใช้งาน