2016-11-10 5 views
0

현재 위도와 경도를 얻기 위해 GPSTracker 클래스를 구현했습니다. 그것은 안드로이드 버전 4.4 이하에 대한 결과를 제공하고 있습니다. 하지만 더 높은 버전에 같은 것을 설치하면 값 (0,0)이 부여됩니다. 어느 곳에서 내가 잘못 될 지 알려줄 수 있습니까?LocationManager 4.4 이상 안드로이드 버전에서 worng location 제공

내 Gpstracker 클래스 : -

public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(Context.LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

내 매니페스트 허가는 다음과 같습니다 -

<permission 
    android:name="goyal.andorid.varun.jaintemplelocator.permission.C2D_MESSAGE" 
    android:protectionLevel="signature" /> 

<uses-permission android:name="goyal.andorid.varun.jaintemplelocator.permission.C2D_MESSAGE" /> 
<!-- This app has permission to register and receive dataf message. --> 
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

<!-- Network State Permissions --> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

`

당신이 요청 권한이 없기 때문에

+0

제안 : Google의 Awareness API –

+0

https://github.com/googlesamples/android-play-location/tree/master/LocationSettings를 사용해보세요. – kId

답변

0

을 저를 도와주세요. 문서에 따르면 :

사용자는 Android 6.0 (API 레벨 23)부터 응용 프로그램을 실행할 때가 아니라 응용 프로그램이 실행되는 동안 응용 프로그램에 권한을 부여합니다.

android.permission.ACCESS_FINE_LOCATION은 (는) danger입니다. 요청하면 요청할 수 있습니다. official manual이 있습니다.

0

위치를 가져 오는 데 GoogleApiClient's fused location provider을 사용할 수 있습니다. 당신은 당신의 gradle 파일에 의존성을 추가해야합니다. 즉

compile 'com.google.android.gms:play-services-location:9.6.1' 

fine_location 권한을 매니페스트

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

에 필요한 추가 그것은 당신이 this.

코드 조각

public class DashboardActivity extends AppCompatActivity implements 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener, 
     ResultCallback<LocationSettingsResult> { 

    private GoogleApiClient googleApiClient; 
    private GoogleApiAvailability apiAvailability; 

    private static final long MIN_TIME_BW_UPDATES = 10000; 
    private static final long FAST_TIME_BW_UPDATES = 3000; 
    private final static int REQUEST_CHECK_SETTINGS = 100; 
    private static final long EXPIRATION_DURATION = 3600000; 

    protected LocationRequest mLocationRequest; 
    protected LocationSettingsRequest mLocationSettingsRequest; 
    private Location location; 
    private LatLng latLng = new LatLng(0, 0); 
    private double latitude; 
    private double longitude; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_dashboard); 
     init(); 
    } 

    private void init() { 
     apiAvailability = GoogleApiAvailability.getInstance(); 
     if (googleApiAvaibility()) { 
      buildGoogleApiClient(); 
      displayLocation(); 
     } 
    } 

    protected void createLocationRequest() { 
     mLocationRequest = LocationRequest.create(); 
     mLocationRequest.setInterval(MIN_TIME_BW_UPDATES); 
     mLocationRequest.setFastestInterval(FAST_TIME_BW_UPDATES); 
     mLocationRequest.setSmallestDisplacement(10); 
     mLocationRequest.setExpirationDuration(EXPIRATION_DURATION); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
     LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder(); 
     builder.addLocationRequest(mLocationRequest); 
     builder.setAlwaysShow(true); 
     mLocationSettingsRequest = builder.build(); 
    } 

    protected synchronized void buildGoogleApiClient() { 
     googleApiClient = new GoogleApiClient.Builder(getApplicationContext()) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    private boolean googleApiAvaibility() { 
     int resultCode = apiAvailability.isGooglePlayServicesAvailable(this); 
     switch (resultCode) { 
      case ConnectionResult.SUCCESS: 
       return true; 
      case ConnectionResult.API_UNAVAILABLE: 
       Dialog dialog = apiAvailability.getErrorDialog(this, ConnectionResult.API_UNAVAILABLE, 200, 
         new DialogInterface.OnCancelListener() { 
          @Override 
          public void onCancel(DialogInterface dialog) { 
           //finish(); 
          } 
         }); 
       dialog.show(); 
       break; 
      case ConnectionResult.SERVICE_MISSING: 
       Dialog dialog1 = apiAvailability.getErrorDialog(this, ConnectionResult.SERVICE_MISSING, 201, 
         new DialogInterface.OnCancelListener() { 
          @Override 
          public void onCancel(DialogInterface dialog) { 
           //finish(); 
          } 
         }); 
       dialog1.show(); 
       break; 
     } 
     return false; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
     //here you will get new latitude and longitude if location is changed 
    } 

    @Override 
    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     switch (requestCode) { 
      case REQUEST_CHECK_SETTINGS: 
       switch (resultCode) { 
        case Activity.RESULT_OK: 
         displayLocation(); 
         break; 
        case Activity.RESULT_CANCELED: 
         //finish(); 
         Toast.makeText(getActivity(), "Please enable location. Otherwise you can not use this application", Toast.LENGTH_LONG).show(); 
         break; 
       } 
       break; 
      default: 

       break; 
     } 
    } 

    @Override 
    public void onConnected(@Nullable Bundle bundle) { 
     createLocationRequest(); 
     checkLocationSettings(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 
     googleApiClient.connect(); 
    } 

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
     googleApiClient.connect(); 
    } 

    @Override 
    public void onResult(@NonNull LocationSettingsResult result) { 
     Status status = result.getStatus(); 
     switch (status.getStatusCode()) { 
      case LocationSettingsStatusCodes.SUCCESS: 
       displayLocation(); 
       break; 
      case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
       try { 
        status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS); 
       } catch (IntentSender.SendIntentException e) { 
        Log.e("Exception", e.toString()); 
       } 
       break; 
      case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
       //showDialog(this,"You have choose never for Location!"); 
       break; 
      default: 
       break; 
     } 
    } 

    protected void checkLocationSettings() { 
     PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi. 
       checkLocationSettings(googleApiClient, mLocationSettingsRequest); 
     result.setResultCallback(this); 
    } 

    private void displayLocation() { 
     if (ActivityCompat.checkSelfPermission(this, 
       Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 250); 
     } else { 
      location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
      if (location != null) { 
       latLng = new LatLng(location.getLatitude(), location.getLongitude()); 
       latitude = location.getLatitude(); 
       longitude = location.getLongitude(); 
       //print latitude longitude here 
      } else { 
       if (googleApiAvaibility()) { 
        buildGoogleApiClient(); 
        googleApiClient.connect(); 
        if (googleApiClient.isConnected()) { 
         LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this); 
        } 
       } 
      } 
     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
     super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
     if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
      if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) { 
       if (location != null) { 
        displayLocation(); 
       } else { 
        //googleApiClient.connect(); 
        if (googleApiAvaibility()) { 
         buildGoogleApiClient(); 
         googleApiClient.connect(); 
        } 
       } 

      } 
     } 
    } 
} 

또한 수처럼 런타임에 허가를 요청할 필요가 Dangerous Permission입니다 이것을 확인하십시오 sample