Pregunta

Un par de otras personas y yo estamos trabajando en una aplicación para android. Se requiere localizar el dispositivo en latitud y longitud. Hemos sido capaces de crear un objeto de la ubicación, pero el objeto siempre está en blanco. Incluso intentamos recrear el código en un proyecto completamente vacío, sino que también fracasó. Aquí está nuestra actividad de las raíces:

package com.app.Locationtest;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;

public class locationtest extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        LocationManager locman =(LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location loc = locman.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (loc==null)
        {
           finish();
        }
    }
}

Este es el manifiesto:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.app.Locationtest"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_GPS" />
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".locationtest"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
    <uses-sdk android:minSdkVersion="8" />

</manifest> 

¿Cómo podemos solucionar este problema?

¿Fue útil?

Solución

A veces, el dispositivo necesita demasiado tiempo para recuperar la ubicación, este es el flujo para recuperar lugares indicados en la sitio androide :

  1. Iniciar aplicación.
  2. Un tiempo después, empezar a escuchar para recibir actualizaciones de los proveedores ubicación deseada.
  3. Mantener una "mejor estimación actual" de la ubicación mediante la filtración de nuevo, pero los arreglos son menos precisos.
  4. dejar de escuchar a las actualizaciones de ubicación.
  5. Tome ventaja de la última y mejor estimación de la localización.

Yo uso un oyente ubicación personalizada y empezar a escuchar a las actualizaciones de ubicación, ya que se ha inicializado mi aplicación, incluso si no estoy mostrando el mapa:

locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
locationListener = new CustomLocationListener(); 
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

Tengo un hilo que está escuchando los lugares, por lo que cuando un par de toques de usuario y llama mi MapView, si la ubicación es nulo, enviamos un msg para el usuario, que esperar mientras Estamos recuperando su ubicación.

Es posible que desee desarrollar un método para elegir la mejor ubicación, ya que la última ubicación quizás no es la mejor ubicación, tratar con esto:

private static final int TWO_MINUTES = 1000 * 60 * 2;

/** Determines whether one Location reading is better than the current Location fix
  * @param location  The new Location that you want to evaluate
  * @param currentBestLocation  The current Location fix, to which you want to compare the new one
  */
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
    // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
      return provider2 == null;
    }
    return provider1.equals(provider2);
 }

Este código se proporciona en la misma página que he vinculado.

Espero que esto ayude!

Otros consejos

getLastKnownLocation () javadoc dice: ".. Si está actualmente se devuelve al proveedor discapacitados, nula."

Por lo tanto, se basa en el GPS pero no encenderlo. Se utiliza a cuestas en otras aplicaciones que usen el GPS.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top