2016-10-09 41 views
0

我想使用谷歌地方API來檢測使用PlaceDetectionApi設備的當前位置。 我期待如果沒有啓用需要的設置來檢測當前位置,則啓動解析應提示用戶啓用位置服務,而無需構建LocationSettings對象並明確調用它來解析。 我錯過了什麼嗎?LocationSettings爲谷歌放置API來檢測當前位置

回答

0

您可以檢查位置模式禁用或手動不,如果禁用,您可以直接打開設置來啓用它,如:

public static boolean isLocationServicesAvailable(Context context) { 
     int locationMode = 0; 
     String locationProviders; 
     boolean isAvailable = false; 

     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(); 
      } 

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

     // boolean coarsePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED); 
     // boolean finePermissionCheck = (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED); 

     return isAvailable; 
    } 

openening設置中禁用的情況下:

if(!isLocationServicesAvailable(this)) { 
      // notify user 
      AlertDialog.Builder dialog = new AlertDialog.Builder(this); 
      dialog.setMessage("enabled"); 
      dialog.setPositiveButton("open GPS", new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
        // TODO Auto-generated method stub 
        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivity(myIntent); 
        //get gps 
       } 
      }); 
      dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 

       @Override 
       public void onClick(DialogInterface paramDialogInterface, int paramInt) { 
        // TODO Auto-generated method stub 

       } 
      }); 
      dialog.show(); 
     } 
+0

我希望有一個更好的通用解決方案,而不是手動檢查互聯網和gps – hsen

+0

我認爲你必須手動檢查它,這就是我所知道的:)) –