2016-10-08 3 views
4

사용자의 위치를 ​​가져 오는 코드를 작성하여 API < 23에서 올바르게 작동하는 코드를 작성할 수 있습니다.하지만 API 23 이상에서는 Log에서 아무것도 반환하지 않습니다.android API에서 사용자 위치 가져 오기

자세한 내용 :
장치의 GPS를 수동으로 활성화합니다. 첫 번째 실행에서 앱 요청 권한과 로그가 반환되지 않습니다.
다음에 앱이 내 준비된 토스트 (제공자 확인)를 반환합니다.

이 내 쓴 코드 :

public class MainActivity extends AppCompatActivity implements LocationListener { 

private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 124; 
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 123; 

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

    // Here, thisActivity is the current activity 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     // Should we show an explanation? 
     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_FINE_LOCATION)) { 

     } else { 

      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_FINE_LOCATION); 
     } 
    } 
    if (ContextCompat.checkSelfPermission(this, 
      Manifest.permission.ACCESS_COARSE_LOCATION) 
      != PackageManager.PERMISSION_GRANTED) { 

     if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
       Manifest.permission.ACCESS_COARSE_LOCATION)) { 

     } else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
        MY_PERMISSIONS_REQUEST_COARSE_LOCATION); 

     } 
    } 

    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; 
    } 
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    String provider = locationManager.getBestProvider(new Criteria(), false); 
    Location location = locationManager.getLastKnownLocation(provider); 
    if (location == null) { 
     Toast.makeText(this, "Check your provider", Toast.LENGTH_SHORT).show(); 
    } else { 
     Log.i("New Location", "lat: " + location.getLatitude()); 
     Log.i("New Location", "lng: " + location.getLongitude()); 
    } 
} 

@Override 
public void onLocationChanged(Location location) { 
    Log.i("Location", "lat: " + location.getLatitude()); 
    Log.i("Location", "lng: " + location.getLongitude()); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

} 안드로이드 API에

+0

는'당신 만 가능 업체를 확인하십시오. 이 경우 공급자를 사용할 수 있는지 여부를 확인하고 사용하지 않으면 사용자가 사용할 수 있도록 설정해야합니다. – AndroidHacker

+0

나는 진실을 거짓으로 바꿨지 만 해결하지 못했습니다. 두 번째하는 법? 나는 거의 새로운 안드로이드입니다. –

답변

5

는 23+ android.permission.ACCESS_FINE_LOCATIONandroid.permission.ACCESS_COARSE_LOCATION의 경우 것은 이것이 "위험"으로 간주 권한을 처리 할 수있는 새로운 방법이 다른 사람 사이에서.

android.permission.ACCESS_FINE_LOCATION을 이미 사용중인 경우 android.permission.ACCESS_COARSE_LOCATION을 처리 할 필요가 없습니다.

Android API 23 이상에서 런타임에 권한을 처리하는 방법을 보여주는 공식 문서에서이 링크를 살펴보십시오.

https://developer.android.com/training/permissions/requesting.html

이것은 또한 당신을 도움이 될 수 있습니다. 권한을 확인하는 방법

https://developer.android.com/guide/topics/location/strategies.html

:

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, 
    Manifest.permission.ACCESS_FINE_LOCATION); 

권한을 요청하는 방법 : 런타임에 권한을 요청하는 경우에도 당신은 여전히에있을 것이라는 점을

if (ContextCompat.checkSelfPermission(thisActivity, 
      Manifest.permission.ACCESS_FINE_LOCATION) 
    != PackageManager.PERMISSION_GRANTED) { 

    // Should we show an explanation? 
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, 
     Manifest.permission.ACCESS_FINE_LOCATION)) { 

     // Show an expanation to the user *asynchronously* -- don't block 
     // this thread waiting for the user's response! After the user 
     // sees the explanation, try again to request the permission. 

    } else { 

     // No explanation needed, we can request the permission. 

     ActivityCompat.requestPermissions(thisActivity, 
      new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
      MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 

     // MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an 
     // app-defined int constant. The callback method gets the 
     // result of the request. 
    } 
} 

주 다음과 같이 Android 매니페스트에 권한 항목을 보관하십시오.

<manifest ... > 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    ... 
    <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> 
    <uses-feature android:name="android.hardware.location.gps" /> 
    ... 
</manifest> 

위의 위치 전략에 대한 링크를 검토하고 허락 한 후에는 누락 된 부분에 대한 세부 정보를 찾을 수 있습니다.

기본적으로 위치 업데이트를 수신하기 위해 수신기를 등록하지 않습니다. onCreate() 메소드 끝에이 행을 추가 한 후 로그에서 위치 갱신 사항을 확인해야합니다. 공급자가 위치가 항상 여기 ** ** 널 (null)을 반환합니다 사용할 수 없습니다 경우 방법`getBestProvider()에서

// Register the listener with the Location Manager to receive location updates 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 
+0

는 문제를 해결하지 못했습니다. 나는 문제가 허락되지 않았다고 생각한다. 토스트를 다시 돌려 받으니. Toast는 "location == null"이 될 때가됩니다. –

+0

업데이트 된 답변을 확인하십시오. 당신은 지금 가야 좋다. –

+0

감사합니다. 당신의 대답은 문제를 해결했습니다. 하지만, load locationUpdate 메소드를 실행합니다 (치트적인 방법). onCreate 내 위치 getter 위치를 얻을 수 없습니다 (내 준비 토스트 반환). 그것을위한 해결책이 아닌가요? 또는이 줄을 제거합니까? –

관련 문제