关于在安卓设备上通过程序来开启/关闭GPS功能的问题已经被讨论过很多次,而答案总是相同的:出于安全和隐私原因,你无法这样做。但对于已root的设备,是否可以通过编辑系统设置来开启GPS呢?
已有root权限的设备可以使用此解决方案。请查看我的个人资料中的一个答案。我现在无法详细说明(正在医院)。但目前需要root和busybox。我正在尝试使其在没有busybox的情况下工作。已经在2.3.5、4.0.1和4.1.2上进行了测试。
http://rapidshare.com/files/3977125468/GPSToggler-20130214.7z
您可以通过编程方式在Android 2.2(API 8)及以下版本中打开/关闭GPS
这是我正在使用的代码
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);
}
}
}
请确保您需要在manifest
文件中添加以下两个权限
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />