【发布时间】:2009-06-26 23:01:34
【问题描述】:
我目前正在编写一个与 GPS 配合使用的 Android 应用。目前我能够确定是否启用了 GPS。我的问题是,如果 GPS 被禁用,我想在应用程序启动时启用它。如何以编程方式执行此操作?
【问题讨论】:
-
取决于纸杯蛋糕的版本。 1.5 显然不允许。
标签: java android gps android-1.5-cupcake
我目前正在编写一个与 GPS 配合使用的 Android 应用。目前我能够确定是否启用了 GPS。我的问题是,如果 GPS 被禁用,我想在应用程序启动时启用它。如何以编程方式执行此操作?
【问题讨论】:
标签: java android gps android-1.5-cupcake
你不能,从 Android 1.5 开始。您最多可以做的是弹出活动以允许用户打开/关闭它。使用android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS 中的操作来制作打开此活动的意图。
【讨论】:
if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
startActivity(myIntent);
}
【讨论】:
这个方法代码可以帮到你
private void turnGPSOnOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){
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);
//Toast.makeText(this, "Your GPS is Enabled",Toast.LENGTH_SHORT).show();
}
}
【讨论】:
您可以使用以下内容:
try {
Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
} catch (Exception e) {
logger.log(Log.ERROR, e, e.getMessage());
}
但它仅在您具有系统签名保护级别时才有效。所以你需要自己做饭来实际使用它:/
【讨论】:
先检查定位服务是否已经开启??
检查定位服务是否启用
public boolean isLocationServiceEnabled(){
LocationManager locationManager = null;
boolean gps_enabled= false,network_enabled = false;
if(locationManager ==null)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
//do nothing...
}
try{
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
//do nothing...
}
return gps_enabled || network_enabled;
}
如果之前关闭了定位服务,那么最终打开
if (isLocationServiceEnabled())) {
//DO what you need...
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Seems Like location service is off, Enable this to show map")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).setNegativeButton("NO THANKS", null).create().show();
}
【讨论】:
您应该在 Play Services 中使用Location Settings Dialog,它会提示用户一键启用位置服务(如有必要)。
【讨论】:
如果您的问题是在 android 的用户级别,这些属性位于:"Settings -> Location -> Use wireless networks" -> "Settings -> Location -> Use GPS satellites"。
但在开发人员处可以使用具有适当权限的类"android.provider.Settings.Secure"。
【讨论】: