0

위도와 경도를 표시하고 싶지만 앱을 다시 시작할 때만 표시됩니다. 앱을 설치하고 처음으로 실행하면 위치가 수신되지 않습니다. 처음으로 현재 위치를 얻는 간단한 방법은 무엇입니까? 내가 뭘 잘못하고있어?Google 위치 서비스 getLastLocation은 처음 앱을 시작할 때 null이됩니다.

private final static String LOG_TAG = MainActivity.class.getName(); 
private GoogleApiClient googleApiClient; 
private Location lastLocation; 
private LocationRequest locationRequest; 
private TextView locationLatitude; 
private TextView locationLongitude; 

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

    locationLatitude = (TextView) findViewById(R.id.latitude_text); 
    locationLongitude = (TextView) findViewById(R.id.longitude_text); 

    buildGoogleApiClient(); 
} 

@Override 
protected void onStart() { 
    super.onStart(); 
    googleApiClient.connect(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    googleApiClient.disconnect(); 
} 

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

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    Log.d(LOG_TAG, "onConnected"); 
    locationRequest = LocationRequest.create(); 
    locationRequest.setInterval(1000); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 

    if(Build.VERSION.SDK_INT < 21){ 
     lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
    } 
    else { 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
     } 
     else{ 
      lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
     } 
    } 


    if(lastLocation != null){ 
     locationLatitude.setText(String.valueOf(lastLocation.getLatitude())); 
     locationLongitude.setText(String.valueOf(lastLocation.getLongitude())); 
    } 
} 

@Override 
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults); 
    if(requestCode == 1){ 
     if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){ 
      if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
      } 
     } 
    } 
} 

@Override 
public void onConnectionSuspended(int i) { 
    Log.d(LOG_TAG, "onConnectionSuspended"); 
} 

@Override 
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 
    Log.d(LOG_TAG, "onConnectionFailed"); 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.d(LOG_TAG, "onLocationChanged"); 
    locationLatitude.setText(String.valueOf(location.getLatitude())); 
    locationLongitude.setText(String.valueOf(location.getLongitude())); 
} 
+0

때때로 마지막 위치를 사용할 수없는 및 null가됩니다 :

이보십시오. 이 시나리오의 환경 설정에서 마지막 위치를 저장하거나 앱을 처음 다운로드 할 때 따라야 할 프로세스로 되돌아가는 것이 좋습니다. – danny117

답변

0

당신은 위치 업데이트를 요청하지 : 나는 API 여기에 24

내 코드가 함께 에뮬레이터에서이 작업을 실행합니다.

@Override 
public void onConnected(@Nullable Bundle bundle) { 
    Log.d(LOG_TAG, "onConnected"); 
    locationRequest = LocationRequest.create(); 
    locationRequest.setInterval(1000); 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
LocationServices.FusedLocationApi.requestLocationUpdates(
      googleApiClient, locationRequest, this); 


    if(Build.VERSION.SDK_INT < 21){ 
     lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
    } 
    else { 
     if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
     } 
     else{ 
      lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
     } 
    } 


    if(lastLocation != null){ 
     locationLatitude.setText(String.valueOf(lastLocation.getLatitude())); 
     locationLongitude.setText(String.valueOf(lastLocation.getLongitude())); 
    } 
} 
+0

당신의 onConnected 메소드를 당신의 것으로 변경했습니다, 그러나 이제는 어플리케이션이 다운되는 것이고 이것은 예외입니다 : 'java.lang.SecurityException : 클라이언트는 PRIORITY_HIGH_ACCURACY 위치를 요청할 수있는 ACCESS_FINE_LOCATION 권한이 있어야합니다.' 그러나 나는 나의 명시에이 허가를 가지고있다. – Konrad

+0

권한 구현을 보여줄 수 있습니까? –

+0

나는 getLastLocation을 요청한 곳과 마찬가지로'LocationServices.FusedLocationApi.requestLocationUpdates ( googleApiClient, locationRequest, this);를 넣었습니다. 지금 예외는 없지만 여전히 나는이 문제에 대해 같은 입장을 취하고 있습니다. 나는 onConnected 메소드 만 변경한다. 나머지는 내 질문의 시작 부분과 같다. (전체 코드를 제공한다.) – Konrad