2016-03-21 67 views
0

我用下面的代码在那里的堆栈溢出检查GPS是否启用或禁用的设备上GPS服务检查,检查GPS是否启用或禁用的设备

public static boolean isLocationEnabled(Context context) { 
    int locationMode = 0; 
    String locationProviders; 

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
     try { 
      locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); 

     } catch (Settings.SettingNotFoundException e) { 
      e.printStackTrace(); 
     } 

     return locationMode != Settings.Secure.LOCATION_MODE_OFF; 

    } else { 
     locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); 
     return !TextUtils.isEmpty(locationProviders); 
    } 


} 

它工作正常在我的设备上(华为G610),我没有问题。然后,我将该应用程序交给了使用三星Galaxy Note的朋友,他告诉他不会通知GPS服务是否启用。

该功能用于在未启用GPS的情况下触发警报对话框,要求用户启用该功能。

我不知道为什么它不在他的设备上工作,您的帮助是高度赞赏。我在询问它背后的原因,不是在某些设备上工作,而是在一些设备上工作。

感谢。

+0

的[我如何找出如果可能的复制Android设备的GPS启用](http://stackoverflow.com/questions/843675/how-do-i-find-out-if-the-gps-of-an-android-device-is-enabled) – Bharatesh

回答

0

您可以使用以下代码检查位置是否已启用。我将在所有设备上工作

LocationManager location_manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
     LocationListener listner = new MyLocationListener(); 


     boolean networkLocationEnabled = location_manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     boolean gpsLocationEnabled = location_manager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     if (networkLocationEnabled || gpsLocationEnabled) { 

      if (location_manager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER) && networkLocationEnabled) { 
       location_manager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 2000, 2000, listner); 
       location_manager 
         .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
      } else if (location_manager.getAllProviders().contains(LocationManager.GPS_PROVIDER) && gpsLocationEnabled) { 
       location_manager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, 2000, 2000, listner); 
       location_manager 
         .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
2

试试这个。
private LocationManager lm;

lm = (LocationManager)   getActivity().getSystemService(getActivity().LOCATION_SERVICE); 
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
    startActivity(intent); 
} 

你manifest文件应设置权限 你需要的是android.permission.ACCESS_COARSE_LOCATIONandroid.permission.ACCESS_FINE_LOCATION主要权限