Не может найти точное местонахождение в android
Я использую этот ниже код, чтобы найти текущее местоположение, но я получил, что некоторые устройства (samsung 7 'и 10'inch и nexus 10'inch) точные текущие местоположения, но unfoirtfully я не могу найти места в samsung s3.
У меня нет ни малейшего понятия, что такое issue.no найти места.
вот мой код:
public class GPSTracker extends Service implements LocationListener
{
private final Context mContext;
//flag for GPS Status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
//The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; //10 metters
//The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
//Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext = context;
getLocation();
}
public Location getLocation()
{
try
{
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled)
{
// no network provider is enabled
}
else
{
this.canGetLocation = true;
//First get location from Network Provider
if (isNetworkEnabled)
{
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
//if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled)
{
if (location == null)
{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null)
{
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
updateGPSCoordinates();
}
}
}
}
}
catch (Exception e)
{
//e.printStackTrace();
Log.e("Error : Location", "Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates()
{
if (location != null)
{
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS()
{
if (locationManager != null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
*/
public double getLatitude()
{
if (location != null)
{
latitude = location.getLatitude();
}
return latitude;
}
/**
* Function to get longitude
*/
public double getLongitude()
{
if (location != null)
{
longitude = location.getLongitude();
}
return longitude;
}
/**
* Function to check GPS/wifi enabled
*/
public boolean canGetLocation()
{
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
*/
public void showSettingsAlert()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
//Setting Dialog Title
alertDialog.setTitle(R.string.GPSAlertDialogTitle);
//Setting Dialog Message
alertDialog.setMessage(R.string.GPSAlertDialogMessage);
//On Pressing Setting button
alertDialog.setPositiveButton(R.string.settings, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
//On pressing cancel button
alertDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.cancel();
}
});
alertDialog.show();
}
/**
* Get list of address by latitude and longitude
* @return null or List<Address>
*/
public List<Address> getGeocoderAddress(Context context)
{
if (location != null)
{
Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);
try
{
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
return addresses;
}
catch (IOException e)
{
//e.printStackTrace();
Log.e("Error : Geocoder", "Impossible to connect to Geocoder", e);
}
}
return null;
}
/**
* Try to get AddressLine
* @return null or addressLine
*/
public String getAddressLine(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String addressLine = address.getAddressLine(0);
return addressLine;
}
else
{
return null;
}
}
/**
* Try to get Locality
* @return null or locality
*/
public String getLocality(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String locality = address.getLocality();
return locality;
}
else
{
return null;
}
}
/**
* Try to get Postal Code
* @return null or postalCode
*/
public String getPostalCode(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String postalCode = address.getPostalCode();
return postalCode;
}
else
{
return null;
}
}
/**
* Try to get CountryName
* @return null or postalCode
*/
public String getCountryName(Context context)
{
List<Address> addresses = getGeocoderAddress(context);
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
String countryName = address.getCountryName();
return countryName;
}
else
{
return null;
}
}
@Override
public void onLocationChanged(Location location)
{
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
Ответы
Ответ 1
Когда местоположение проверяется на точность. Если он недостаточно точен, не обрабатывайте его.
@Override
public void onLocationChanged(Location location) {
if (!location.hasAccuracy()) {
return;
}
if (location.getAccuracy() > 5) {
return;
}
// do something with location accurate to 5 meters here.
}
Ответ 2
Сделайте это, Загрузите приложение на свое устройство, перейдите в открытое небо, запустите приложение, подождите 2 минуты. Вернитесь в офис внутри, а затем выполните над кодом
Это сработало для меня.
Надеюсь, это поможет вам.
Ответ 3
Мы работали на устройствах Samsung и имели проблемы. Просто убедитесь в следующем:
- GPS включен (уровень улицы также должен быть включен)
- включена мобильная сеть (если требуется, также разрешите использовать параметр "Использовать пакетные данные" )
- Загрузите и установите некоторые сторонние виджеты в телефоне и дождитесь появления/обновления координат в виджетах. (Это связано с тем, что у виджетов есть встроенная в них концепция тайм-аута и многократно пытались получить координаты)
- Откройте Google-карты с устройства и проверьте, не идентифицировано ли ваше местоположение. (Иногда мы наблюдали, что Карты Google смогут определять координаты там, где мы не смогли бы!)
- Убедитесь, что сигнал GPS-спутника на панели заголовка уведомлений мигает.
- При необходимости установите таймер для обновления и добавьте сообщения для тоста, чтобы отобразить длинные латы после получения.
Для устройства samsung в первый раз координаты GPS не сразу отражаются (он равен нулю и может длиться до получаса:( Как раздражает!!). Итак, мы ждали вне офиса для некоторое время до получения координат GPS.
Ответ 4
У меня была та же проблема. Дело в следующем: Вам нужен промежуток времени между вашими "requestLocationUpdates" и "getLastKnownLocation"
Попробуйте запустить requestLocationUpdates в методе onStart или onCreate.
protected void onStart() {
super.onStart();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
Это активирует ваш GPS. Вы должны подождать несколько секунд, пока не найдете несколько мест.
Поэтому я помещаю метод getlastKnownLocation в OnClickEvent. Если местоположение не найдено, оно просто отображает Toast.
public void onClick (View v) {
m_CurrentLocation = m_LocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (m_CurrentLocation != null)
// Your action with the last known location
else
Toast.makeText(YourActivity.this, "No GPS Location found", Toast.LENGTH_SHORT).show();
}
Ответ 5
Существует множество ошибок с LocationManager, почему бы вам не попробовать использовать плавный провайдер местоположения с LocationClient. Разработчики в Google рекомендовали это также во время последнего ввода/вывода Google.
Если устройство работает на версиях старше Froyo, у которых нет игровых сервисов, нет причин использовать LocationManager.