Detect GPS ON/OFF status using android.provider.Settings.Secure

android.provider.Settings.Secure is secure system settings, containing system preferences that applications can read but are not allowed to write. These are for preferences that the user must explicitly modify through the system UI or specialized APIs for those values, not modified directly by applications.

Start from API level 8, Android 2.2, Settings.Secure.isLocationProviderEnabled() is added as helper method for determining if a location provider is enabled.

Detect GPS ON/OFF status using android.provider.Settings.Secure

package com.AndroidGPS;

import android.app.Activity;
import android.content.ContentResolver;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;

public class AndroidGPS extends Activity {

TextView textGpsStatus;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textGpsStatus = (TextView)findViewById(R.id.gpsstatus);

}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
displayGpsStatus();
}

private void displayGpsStatus(){
ContentResolver contentResolver = getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
if(gpsStatus){
textGpsStatus.setText("GPS: ON");
}else{
textGpsStatus.setText("GPS: OFF");
}
}
}


Remark:
Another method setLocationProviderEnabled() is also provided to enable or disable a single location provider. But up to this writing, I can't make it work! Also, according to Settings.Secure document, secure system settings can be read by applications but cannot be write. I don't know what is the purpose of the method setLocationProviderEnabled()!

Related:
- How to check if GPS is currently enabled or disabled
- Start Location setting if GPS disabled

0 Response to "Detect GPS ON/OFF status using android.provider.Settings.Secure"

Posting Komentar