Reputation: 7582
This question about turning on/off GPS programatically on android has been discussed many times, and the answer is always the same: You can't for security/privacy reasons. But is there any way for rooted devices to turn on gps with some edit in system settings..
Upvotes: 4
Views: 2350
Reputation: 972
There is a working solution fot rooted. See in one of my answers in profile. I cannot elaborate right now (in hospital). But currently you need root and busybox. I'm trying to make it working without busybox. Tested with 2.3.5 4.0.1 and 4.1.2
http://rapidshare.com/files/3977125468/GPSToggler-20130214.7z
Upvotes: 2
Reputation: 35783
You can Turn ON/OFF GPS programmatically up-to Android 2.2(API 8)
Here is the code I am using
public class GpsOnOff extends Activity implements OnClickListener {
Button onButton;
Button offButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
onButton = (Button) findViewById(R.id.btnON);
offButton = (Button) findViewById(R.id.btnOFF);
onButton.setOnClickListener(this);
offButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v==onButton){
//this will work upto 2.2 api only
turnGPSOn();
//this will work for all but it Navigate to
GPS setting screen only
//not change settings automatically
/*Intent in = new Intent(android.provider.Settings
.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(in);*/
Toast.makeText(getApplicationContext(),
"gps enabled", 1).show();
}
else if(v==offButton){
turnGPSOff();
Toast.makeText(getApplicationContext(),
"gps disabled", 1).show();
}
}
private void turnGPSOn(){
String provider = Settings.Secure
.getString(getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget
.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(
getContentResolver(), Settings.Secure
.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget
.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
}
Make sure you need to add below two permissions to manifest
file
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
Upvotes: 0