위치 도구를 사용하여 Android에서 모바일 장치의 현재 위도 및 경도를 얻으려면 어떻게해야합니까?
답변
를 사용하십시오 LocationManager
.
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
에 대한 호출이 getLastKnownLocation()
차단되지 않습니다.null
현재 사용 가능한 위치가없는 경우 됩니다. 대신 메소드에 a LocationListener
를 전달 하여 위치를 비동기식으로 업데이트 하려고합니다 .requestLocationUpdates()
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
GPS를 사용하려면 애플리케이션에 ACCESS_FINE_LOCATION
권한 을 부여해야합니다 .
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
GPS를 사용할 수없는 경우 에 대한 ACCESS_COARSE_LOCATION
권한 을 추가 하고 방법으로 위치 제공 업체를 선택할 수도 있습니다.getBestProvider()
.
답변
다음은 LocationFinder
GPS 위치를 찾는 클래스 입니다. 이 클래스는 MyLocation
비즈니스를 수행하는 을 (를) 호출 합니다.
위치 파인더
public class LocationFinder extends Activity {
int increment = 4;
MyLocation myLocation = new MyLocation();
// private ProgressDialog dialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intermediat);
myLocation.getLocation(getApplicationContext(), locationResult);
boolean r = myLocation.getLocation(getApplicationContext(),
locationResult);
startActivity(new Intent(LocationFinder.this,
// Nearbyhotelfinder.class));
GPSMyListView.class));
finish();
}
public LocationResult locationResult = new LocationResult() {
@Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
double Longitude = location.getLongitude();
double Latitude = location.getLatitude();
Toast.makeText(getApplicationContext(), "Got Location",
Toast.LENGTH_LONG).show();
try {
SharedPreferences locationpref = getApplication()
.getSharedPreferences("location", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = locationpref.edit();
prefsEditor.putString("Longitude", Longitude + "");
prefsEditor.putString("Latitude", Latitude + "");
prefsEditor.commit();
System.out.println("SHARE PREFERENCE ME PUT KAR DIYA.");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
// handler for the background updating
}
내 위치
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
// Toast.makeText(context, " Yaha Tak AAya", Toast.LENGTH_LONG).show();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
@Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
답변
와 google
가지 매우 자주 변경 : 나를 위해 일 이전 답변의 비.
이 Google 교육을 바탕으로 사용하는 방법은 다음과 같습니다.
융합 위치 제공자
이를 위해서는 Google Play 서비스 설정이 필요합니다
활동 수업
public class GPSTrackerActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
Location mLastLocation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
public void onConnected(Bundle bundle) {
try {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
Intent intent = new Intent();
intent.putExtra("Longitude", mLastLocation.getLongitude());
intent.putExtra("Latitude", mLastLocation.getLatitude());
setResult(1,intent);
finish();
}
} catch (SecurityException e) {
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
용법
당신의 활동에서
Intent intent = new Intent(context, GPSTrackerActivity.class);
startActivityForResult(intent,1);
그리고이 방법
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
Bundle extras = data.getExtras();
Double longitude = extras.getDouble("Longitude");
Double latitude = extras.getDouble("Latitude");
}
}
답변
이것을 사용하여 Current latlng를 얻을 수 있습니다
`
public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private String provider;
private MyLocationListener mylistener;
private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
String a=""+location.getLatitude();
Toast.makeText(getApplicationContext(), a, 222).show();
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Initialize the location fields
Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(),
Toast.LENGTH_SHORT).show()
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
}
`
답변
위의 솔루션도 정확하지만 위치가 null 인 경우 앱이 중단되거나 제대로 작동하지 않습니다. 안드로이드의 위도 및 경도를 얻는 가장 좋은 방법은 다음과 같습니다.
Geocoder geocoder;
String bestProvider;
List<Address> user = null;
double lat;
double lng;
LocationManager lm = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
bestProvider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(bestProvider);
if (location == null){
Toast.makeText(activity,"Location Not found",Toast.LENGTH_LONG).show();
}else{
geocoder = new Geocoder(activity);
try {
user = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
lat=(double)user.get(0).getLatitude();
lng=(double)user.get(0).getLongitude();
System.out.println(" DDD lat: " +lat+", longitude: "+lng);
}catch (Exception e) {
e.printStackTrace();
}
}
답변
가장 좋은 방법은
권한 매니페스트 파일 추가
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
그런 다음 GPS 위치를 얻거나 GPS 위치를 사용할 수없는 경우이 기능은 네트워크 위치를 반환합니다.
public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
assert lm != null;
isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location networkLoacation = null, gpsLocation = null, finalLoc = null;
if (isGpsEnabled)
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkLocationEnabled)
networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null && networkLoacation != null) {
//smaller the number more accurate result will
if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
return finalLoc = networkLoacation;
else
return finalLoc = gpsLocation;
} else {
if (gpsLocation != null) {
return finalLoc = gpsLocation;
} else if (networkLoacation != null) {
return finalLoc = networkLoacation;
}
}
return finalLoc;
}
답변
업데이트 2020 : Kotlin Coroutine을 사용하여 장치의 위도, 언어 및 주소 얻기
이것은 오래된 질문이며 대부분의 답변은 구식입니다. 이것이 내 앱을 지금하는 방법입니다.
이 클래스는 지오 코딩을 사용하여 장치 위치 및 장치 주소의 반환 목록을 추적하는 데 도움이됩니다. 유틸리티 클래스에 넣으십시오.
import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.*
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import com.bmw.weatherapp.R
import kotlinx.coroutines.*
import java.io.IOException
import java.lang.ref.WeakReference
import java.util.*
import kotlin.coroutines.CoroutineContext
/**
* Use GPS or Network Provider to get Device Location
*/
class DeviceLocationTracker(context: Context, deviceLocationListener: DeviceLocationListener) : LocationListener, CoroutineScope {
private var deviceLocation: Location? = null
private val context: WeakReference<Context>
private var locationManager: LocationManager? = null
private var deviceLocationListener: DeviceLocationListener
private val job = Job()
override val coroutineContext: CoroutineContext
get() = job + Dispatchers.Main
init {
this.context = WeakReference(context)
this.deviceLocationListener = deviceLocationListener
initializeLocationProviders()
}
private fun initializeLocationProviders() {
//Init Location Manger if not already initialized
if (null == locationManager) {
locationManager = context.get()
?.getSystemService(Context.LOCATION_SERVICE) as LocationManager
}
locationManager?.apply {
// flag for GPS status
val isGPSEnabled = isProviderEnabled(LocationManager.GPS_PROVIDER)
// flag for network status
val isNetworkEnabled = isProviderEnabled(LocationManager.PASSIVE_PROVIDER)
//If we have permission
if (ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context.get()!!, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//First Try GPS
if (isGPSEnabled) {
requestLocationUpdates(
LocationManager.GPS_PROVIDER,
UPDATE_FREQUENCY_TIME,
UPDATE_FREQUENCY_DISTANCE.toFloat(), this@DeviceLocationTracker)
deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
} else {
// Show alert to open GPS
context.get()?.apply {
AlertDialog.Builder(this)
.setTitle(getString(R.string.title_enable_gps))
.setMessage(getString(R.string.desc_enable_gps))
.setPositiveButton(getString(R.string.btn_settings)
) { dialog, which ->
val intent = Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS)
startActivity(intent)
}.setNegativeButton(getString(R.string.btn_cancel))
{ dialog, which -> dialog.cancel() }.show()
}
}
//If failed try using NetworkManger
if(null==deviceLocation && isNetworkEnabled) {
requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
0, 0f,
this@DeviceLocationTracker)
deviceLocation = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
}
}
}
/**
* Stop using GPS listener
* Must call this function to stop using GPS
*/
fun stopUpdate() {
if (locationManager != null) {
locationManager!!.removeUpdates(this@DeviceLocationTracker)
}
}
override fun onLocationChanged(newDeviceLocation: Location) {
deviceLocation = newDeviceLocation
launch(Dispatchers.Main) {
withContext(Dispatchers.IO) {
var addressList: List<Address?>? = null
try {
addressList = Geocoder(context.get(),
Locale.ENGLISH).getFromLocation(
newDeviceLocation.latitude,
newDeviceLocation.longitude,
1)
deviceLocationListener.onDeviceLocationChanged(addressList)
Log.i(TAG, "Fetch address list"+addressList)
} catch (e: IOException) {
Log.e(TAG, "Failed Fetched Address List")
}
}
}
}
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
interface DeviceLocationListener {
fun onDeviceLocationChanged(results: List<Address>?)
}
companion object {
// The minimum distance to change Updates in meters
private const val UPDATE_FREQUENCY_DISTANCE: Long = 1 // 10 meters
// The minimum time between updates in milliseconds
private const val UPDATE_FREQUENCY_TIME: Long = 1 // 1 minute
private val TAG = DeviceLocationTracker::class.java.simpleName
}
}
GPS가 비활성화 된 경우 경고 대화 상자에 문자열 추가
<string name="title_enable_gps">Enable GPS</string>
<string name="desc_enable_gps">GPS is not enabled. Do you want to go to settings menu?</string>
<string name="btn_settings">Open Settings</string>
<string name="btn_cancel">Cancel</string>
Android 매니페스트에 이러한 권한을 추가하고 앱 시작시 요청
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
용법
수업 DeviceLocationListener
에서 구현Activity/Fragment
class MainActivity : AppCompatActivity, DeviceLocationTracker.DeviceLocationListener {
onDeviceLocationChanged
콜백을 재정의 합니다. 당신은 현재 위치를 얻을 것이다onDeviceLocationChanged
override fun onDeviceLocationChanged(results: List<Address>?) {
val currntLocation = results?.get(0);
currntLocation?.apply {
currentlLat = latitude
currentLng = longitude
Country = countryCode
cityName = getAddressLine(0)
}
}
추적을 시작하려면 방법으로 DeviceLocationTracker
개체를 만드 onCreate
십시오. 전달 Activity
과 같은 컨텍스트 및이로 DeviceLocationListener
.
private lateinit var deviceLocationTracker: DeviceLocationTracker
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
...
deviceLocationTracker= DeviceLocationTracker(this, this)
즉, 이제에서 위치 업데이트를 시작합니다 onDeviceLocationChanged
.