0

하루 종일 내 안드로이드 앱에서 장치의 현재 위치 (지속적인 업데이트가 아님)를 얻으려고했습니다. GoogleApiClient를 사용하고있었습니다. 위치가 항상 null을 반환 했으므로 FusedLocationApi.requestLocationUpdates를 사용하면 위치를 수정할 수 있습니다. 그래서 그렇게했습니다.FusedLocationApi.requestLocationUpdates - onLocationChanged가 호출되지 않습니다.

이제는 제대로 작동하지 않습니다. 여기 내 코드가있다. 누군가가 나에게 무엇을해야한다고 말하면 나는 정말로 의무감을 느낍니다.

고맙습니다.

package com.example.root.restaurant; 
    import android.Manifest; 
    import android.annotation.TargetApi; 
    import android.content.pm.PackageManager; 
    import android.location.Location; 
    import android.location.LocationManager; 
    import android.os.Build; 
    import android.provider.ContactsContract; 
    import android.support.annotation.NonNull; 
    import android.support.annotation.Nullable; 
    import android.support.annotation.RequiresApi; 
    import android.support.v4.app.ActivityCompat; 
    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.widget.RelativeLayout; 
    import android.widget.Button; 
    import android.graphics.Color; 
    import android.widget.EditText; 
    import android.view.View; 
    import android.widget.TextView; 
    import android.content.Intent; 
    import android.widget.Toast; 

    import com.google.android.gms.common.ConnectionResult; 
    import com.google.android.gms.common.api.GoogleApiClient; 
    import com.google.android.gms.location.FusedLocationProviderApi; 
    import com.google.android.gms.location.LocationListener; 
    import com.google.android.gms.location.LocationRequest; 
    import com.google.android.gms.location.LocationServices; 
    import com.google.android.gms.maps.CameraUpdateFactory; 
    import com.google.android.gms.maps.GoogleMap; 
    import com.google.android.gms.maps.model.LatLng; 
    import com.google.android.gms.maps.model.MarkerOptions; 

    import org.w3c.dom.Text; 

    import java.util.List; 

    public class MainActivity extends AppCompatActivity implements   GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 

     private static GoogleApiClient googleApiClient; 
     private Location mLastLocation; 
     TextView t; 
     private Double myLatitude; 
     private Double myLongitude; 
     private LocationRequest locationRequest; 
     private FusedLocationProviderApi locationProvider = LocationServices.FusedLocationApi; 

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

    Log.i("jennysMsg", "..............................Started"); 

    t = (TextView) findViewById(R.id.textView2); 

    locationRequest = new LocationRequest(); 
    locationRequest.setInterval(15 * 1000); 
    locationRequest.setFastestInterval(15 * 1000); 
    locationRequest.setSmallestDisplacement(0); 
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); 


    googleApiClient = new GoogleApiClient.Builder(this) 
      .addConnectionCallbacks(this) 
      .addOnConnectionFailedListener(this) 
      .addApi(LocationServices.API) 
      .setAccountName("kfoozminus") 
      .build(); 
    if (googleApiClient != null) { 
     Log.i("jennysMsg", ".....................................it's not nul!!!"); 
     googleApiClient.connect(); 
    } 
} 

@Override 
public void onConnected(@Nullable Bundle bundle) { 

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
    if (location == null) { 
     requestLocationUpdates(); 
    } 
    else { 
     myLatitude = location.getLatitude(); 
     myLongitude = location.getLongitude(); 
     t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude)); 
    } 
} 

private void requestLocationUpdates() { 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this); 
} 

@Override 
public void onConnectionSuspended(int i) { 

} 

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

} 

@Override 
public void onLocationChanged(Location location) { 

    myLatitude = location.getLatitude(); 
    myLongitude = location.getLongitude(); 
    t.setText("Location : " + String.valueOf(myLatitude) + String.valueOf(myLongitude)); 

} 

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

@Override 
protected void onResume() { 
    super.onResume(); 
    if(googleApiClient.isConnected()) { 
     requestLocationUpdates(); 
    } 
} 

@Override 
protected void onPause() { 
    super.onResume(); 
    LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this); 
} 

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

답변

0

당신이 정확한 위치에 대한 대략적인 위치 또는 ACCESS_FINE_LOCATION를 원한다면 당신이 당신의 manifest.Either ACCESS_COARSE_LOCATION에 권한을 추가 어떠했는지를 확인해야 우선.

두 번째 코드는 onStart 메서드에서 googleApiClient.connect() 주석 처리를 제거해야한다는 점을 제외하고는 괜찮은 것처럼 보입니다.

에뮬레이터를 사용하는 경우 에뮬레이터를 사용하는 경우 위치를 반환 할 수 없지만 대신 에뮬레이터 옆에 맞춤 위치 (경도, 위도)를 만들어야합니다. 설정/아이콘을 클릭하면 경도와 위도를 찾고 설정할 수 있습니다 경도와 위도를 수동으로 클릭하고 보내면 좋을 것입니다. 여전히 작동하지 않는 경우 에뮬레이터를 다시 시작하거나 실제 장치를 사용하여이 코드를 테스트 해보십시오.

업데이트 : 이 에뮬레이터 어떠했는지를 확인하시기 바랍니다 구글 패키지를 포함, 당신은 구글 플레이 서비스에 항상 당신이 말한

+0

모두를 null를 돌려줍니다 servide 구글 플레이에 액세스하려고하는 동안 구글 패키지가 포함되어 있지 않은 경우, 나는 모두했다. 작동하지 않습니다. googleApiClient.connect()가 처음에는 onStart() 메소드에 있었지만 작동하지 않아 onCreate 메소드로 가져갔습니다. genymotion (사용자 정의 경도/위도 사용)과 내 안드로이드 전화에서 테스트했습니다. 작동하지 않습니다. ( – kfoozminus