从2.2开始,官方提供了
public static final void setLocationProviderEnabled (ContentResolver cr, String provider, boolean enabled)
Since: API Level 8
Thread-safe method for enabling or disabling a single location provider.
Parameters
cr the content resolver to use
provider the location provider to enable or disable
enabled true if the provider should be enabled
方法开启gps和网络定位,但实际上木有权限进行此操作,配置了WRITE_SECURE_SETTINGS权限后还是提示木有此权限,
查了以后有该权限属于系统级应用的权限,非系统应用木有此权限。网上有人提供的方法如下,不需要任何权限,
可以打开gps。
private void toggleGPS()
{
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
try
{
PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
Toast.makeText(getApplicationContext(), "测试", Toast.LENGTH_SHORT)
.show();
}
catch (CanceledException e)
{
e.printStackTrace();
}
}
测试后发现,在2.2、2.3系统的手机上可以打开,但4.0、4.1系统上的无法打开。对比了4.0以上系统设置和2.2系统设置的源码,发现木有改变,但都是无法开启gps。
public static final void setLocationProviderEnabled (ContentResolver cr, String provider, boolean enabled)
Since: API Level 8
Thread-safe method for enabling or disabling a single location provider.
Parameters
cr the content resolver to use
provider the location provider to enable or disable
enabled true if the provider should be enabled
方法开启gps和网络定位,但实际上木有权限进行此操作,配置了WRITE_SECURE_SETTINGS权限后还是提示木有此权限,
查了以后有该权限属于系统级应用的权限,非系统应用木有此权限。网上有人提供的方法如下,不需要任何权限,
可以打开gps。
private void toggleGPS()
{
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
try
{
PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
Toast.makeText(getApplicationContext(), "测试", Toast.LENGTH_SHORT)
.show();
}
catch (CanceledException e)
{
e.printStackTrace();
}
}
测试后发现,在2.2、2.3系统的手机上可以打开,但4.0、4.1系统上的无法打开。对比了4.0以上系统设置和2.2系统设置的源码,发现木有改变,但都是无法开启gps。