2016-09-17 2 views
0

lastknown 위치를 가져 오려고하지만 null 값을 제공하고 있습니다. GPS를 사용할 수 있는지 여부를 테스트 한 결과 사실입니다.Android에서 LastKnownLocation 가져 오기

심지어 Google지도에 들어가서 내 위치를 지적했지만 (위치 데이터가 삭제 될 수 있다고 생각 함) 여전히 작동하지 않았습니다. 여기

내 코드

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      return; 
     } 
     boolean isgps=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     Log.v("is GPs Enabled",isgps+""); 
     Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     updateNewLocation(location); 
    } 

    private void updateNewLocation(Location location) { 
     TextView myLocationText=(TextView)findViewById(R.id.myLocation); 
     if(location!=null){ 
      double lat=location.getLatitude(); 
      double lng=location.getLongitude(); 
      myLocationText.setText("lat:"+lat+"\nlong:"+lng); 
      Log.v("Location","lat:"+lat+"\nlong:"+lng); 
     } 
    } 
+0

도움이 될 수도 있습니다. http://stackoverflow.com/a/10524443/6178443 –

+1

[getLastKnownLocation 메서드는 항상 null을 반환 할 수 있습니다.] (http://stackoverflow.com/questions/6854099/getlastknownlocation-method-always -returns-null) –

답변

0

입니다 안녕하세요 왜 이전의 위도와 longitude.Most은 아마 null.It 업데이트 시간이 걸립니다을 retrun하고 이전 위도 LNG를 반환를 반환 .IT getLastKnownLocation를 사용하려고 그것은 아주 오래되거나 새로운 나이 일 수 있습니다. 정확하고 정확하지 않습니다. 그래서, 당신은 더 나은 새로운 접근 방법을 찾으러갑니다.

난 그냥 구글 융합 된 API가 어떤 updation 또는 current.Its 매우 정확합니다.

프로젝트에서 API를 융합하는 방법. 작은 예제를 보여 드리겠습니다.

1 단계 메이크업이 클래스 GoogleLocationService.java

public class GoogleLocationService { 
private GoogleServicesCallbacks callbacks = new GoogleServicesCallbacks(); 
LocationUpdateListener locationUpdateListener; 
Context activity; 
protected GoogleApiClient mGoogleApiClient; 
protected LocationRequest mLocationRequest; 

public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 30000; 


public GoogleLocationService(Context activity, LocationUpdateListener locationUpdateListener) { 
    this.locationUpdateListener = locationUpdateListener; 
    this.activity = activity; 
    buildGoogleApiClient(); 
} 

protected synchronized void buildGoogleApiClient() { 
    //Log.i(TAG, "Building GoogleApiClient"); 
    mGoogleApiClient = new GoogleApiClient.Builder(activity) 
      .addConnectionCallbacks(callbacks) 
      .addOnConnectionFailedListener(callbacks) 
      .addApi(LocationServices.API) 
      .build(); 
    createLocationRequest(); 
    mGoogleApiClient.connect(); 
} 

protected void createLocationRequest() { 
    mLocationRequest = new LocationRequest(); 
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

} 

private class GoogleServicesCallbacks implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

    @Override 
    public void onConnected(Bundle bundle) { 
     startLocationUpdates(); 
    } 

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

    @Override 
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 

     if (connectionResult.getErrorCode() == ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED) { 
      Toast.makeText(activity, "Google play service not updated", Toast.LENGTH_LONG).show(); 

     } 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (location.hasAccuracy()) { 
      if (location.getAccuracy() < 30) { 
       locationUpdateListener.updateLocation(location); 
      } 
     } 
    } 
} 

private static boolean locationEnabled(Context context) { 
    boolean gps_enabled = false; 
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    try { 
     gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
    return gps_enabled; 
} 

private boolean servicesConnected(Context context) { 
    return isPackageInstalled(GooglePlayServicesUtil.GOOGLE_PLAY_STORE_PACKAGE, context); 
} 

private boolean isPackageInstalled(String packagename, Context context) { 
    PackageManager pm = context.getPackageManager(); 
    try { 
     pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES); 
     return true; 
    } catch (PackageManager.NameNotFoundException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 


public void startUpdates() { 
    /* 
    * Connect the client. Don't re-start any requests here; instead, wait 
    * for onResume() 
    */ 
    if (servicesConnected(activity)) { 
     if (locationEnabled(activity)) { 
      locationUpdateListener.canReceiveLocationUpdates(); 
      startLocationUpdates(); 
     } else { 
      locationUpdateListener.cannotReceiveLocationUpdates(); 
      Toast.makeText(activity, "Unable to get your location.Please turn on your device Gps", Toast.LENGTH_LONG).show(); 
     } 
    } else { 
     locationUpdateListener.cannotReceiveLocationUpdates(); 
     Toast.makeText(activity, "Google play service not available", Toast.LENGTH_LONG).show(); 
    } 
} 

//stop location updates 
public void stopUpdates() { 
    stopLocationUpdates(); 
} 

//start location updates 
private void startLocationUpdates() { 

    if (checkSelfPermission(activity, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(activity, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     return; 
    } 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, callbacks); 
    } 
} 

public void stopLocationUpdates() { 
    if (mGoogleApiClient.isConnected()) { 
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, callbacks); 
    } 
} 

public void startGoogleApi() { 
    mGoogleApiClient.connect(); 
} 

public void closeGoogleApi() { 
    mGoogleApiClient.disconnect(); 
} 

} 

2 단계. 이 인터페이스 LocationUpdateListener.java

public interface LocationUpdateListener { 

/** 
* Called immediately the service starts if the service can obtain location 
*/ 
void canReceiveLocationUpdates(); 

/** 
* Called immediately the service tries to start if it cannot obtain location - eg the user has disabled wireless and 
*/ 
void cannotReceiveLocationUpdates(); 

/** 
* Called whenever the location has changed (at least non-trivially) 
* @param location 
*/ 
void updateLocation(Location location); 

/** 
* Called when GoogleLocationServices detects that the device has moved to a new location. 
* @param localityName The name of the locality (somewhere below street but above area). 
*/ 
void updateLocationName(String localityName, Location location); 
} 

단계 3. 당신이 위치

private GoogleLocationService googleLocationService; 

googleLocationService = new GoogleLocationService(context, new LocationUpdateListener() { 
    @Override 
    public void canReceiveLocationUpdates() { 
    } 

    @Override 
    public void cannotReceiveLocationUpdates() { 
    } 

    //update location to our servers for tracking purpose 
    @Override 
    public void updateLocation(Location location) { 
     if (location != null) { 
      Timber.e("updated location %1$s %2$s", location.getLatitude(), location.getLongitude()); 

     } 
    } 

    @Override 
    public void updateLocationName(String localityName, Location location) { 

     googleLocationService.stopLocationUpdates(); 
    } 
}); 
googleLocationService.startUpdates(); 


and call this onDestroy 
if (googleLocationService != null) { 
    googleLocationService.stopLocationUpdates(); 
} 

덕분에이 도움말을 희망 얻으려면이 코드 조각을합니다.

관련 문제