Android 4.4 API 19 LocationListener onLocationChanged从未触发,但locationManager.getLastKnownLocation已更新

时间:2015-02-13 17:40:56

标签: gps android-4.4-kitkat locationmanager locationlistener

Android新手...我正在使用带有API 19 KitKat模拟器(和项目)的Android Studio 1.0.2来测试gps处理...(也在手机上测试了相同的结果)

感谢您的帮助! :)

telnet - > geo fix 24 24确实改变了locationManager.getLastKnownLocation!但是不会火上浇油吗? (我从来没有得到"触发"登录记录了getlastknownlocation的logcat)

输出:纬度:24.0。经度:24.0。提供者:gps at 1423821600000 (我知道我需要格式化日期而不是gettime(),更担心onlocationchanged)...

我已经采取了其他调试步骤... locationManager.getLastKnownLocation()。getprovider()是gps ...我硬编码到locationmanager提供程序来测试不同的东西,这似乎是大多数人在我遇到的问题用Google搜索(当geo fix使用gps时使用network_service而不是gps)...

我看到的每个教程都是一个实现locationListener的intentservice或activity,但是我希望将位置监听器单独剥离......也许这不可能,或者只是模拟器出现问题?

我创建一个类并将其传递给Context(Intent)

public class TestGPS{

    private Context context;
    private MyLocationListener locationListener;
    private LocationManager locationManager;

    public TestGPS(Context callingContext) { 
        this.context = callingContext;

        // Acquire a reference to the system Location Manager
        this.locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE);

        // Define a listener that responds to location updates
        this.locationListener = new MyLocationListener(this.context, locationManager);
    }

此课程使用

请求新的gps坐标
public void doStuff(){
    String provider = null;
    boolean gpsEnabledLocation = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    boolean networkEnabledLocation = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (networkEnabledLocation)
    {
        provider = LocationManager.NETWORK_PROVIDER;
    }
    else if (gpsEnabledLocation)
    {
        provider = LocationManager.GPS_PROVIDER;
    }
        this.locationManager.requestLocationUpdates(provider, 1000, 0, this.locationListener);

    while (!this.locationListener.Triggered)
    {
        Location lastLocation = this.locationManager.getLastKnownLocation(provider);
        if (lastLocation != null) {
            String lastLocationString = "Latitude: " + lastLocation.getLatitude() + ". Longitude: " + lastLocation.getLongitude() + ". Provided by: " + lastLocation.getProvider() + " at " + lastLocation.getTime();
            Log.i("locationManager", lastLocationString);
        }

        Thread.sleep(5 * 1000);
    }

    this.locationManager.removeUpdates(this.locationListener);
}

然后是实现locationlistener

的类
public class MyLocationListener implements LocationListener {

    public boolean Triggered = false;

    @Override
    public void onLocationChanged(Location location) {
        Log.i("onLocationChanged", "Triggered");
        this.Triggered = true;
    }

    ... the other 3 functions
}

再次感谢!

0 个答案:

没有答案