如何在Android Cupcake中以编程方式启用GPS

Chi*_*han 27 java gps android android-1.5-cupcake

我目前正在Android中编写一个与GPS配合使用的应用程序.目前我能够确定GPS是否已启用.我的问题是,如果禁用,我想在应用启动时启用GPS.我怎么能这样做程序化?

Com*_*are 51

你不能,从Android 1.5开始.您可以做的最多就是弹出活动以允许用户打开/关闭它.使用保留的操作android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS来制作Intent以打开此活动.

  • 由于隐私原因,它被禁用.如果用户想要关闭GPS,则用户应关闭GPS,周期. (24认同)
  • 为什么这个禁用?为什么不允许开发人员切换这个?Power Control小部件可以,所以我们也应该能够.你不觉得吗? (3认同)

TS.*_*.xy 15

if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
    Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS );
    startActivity(myIntent);
}
Run Code Online (Sandbox Code Playgroud)

  • 这个代码在android 2.2上没有为我编译,因为.isProviderEnabled不是LocationManager上的静态方法.我的工作代码如下(格式化道歉)LocationManager locationManager =(LocationManager)getSystemService(LOCATION_SERVICE); if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(myIntent); } (8认同)

Dwi*_* Ji 6

这个方法代码可以帮到你

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();
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的**这可以达到2.2(sdk 8)**.有关详细信息,请参阅[以编程方式启用GPS,如Tasker](http://stackoverflow.com/a/5305835/383414) (2认同)