无法获得用户位置

时间:2014-09-02 06:07:19

标签: android android-service android-location

我正在尝试将用户位置设置为网络位置或gps位置或两者。因为我正在运行实现LocationListener的后台服务。我还在清单文件中添加了所有必需权限。这是我的服务

public class GetLocation extends Service implements LocationListener {

    LocationManager lm;
    Location networkLocation, gpsLocation;

    @Override
    public void onCreate() {
        super.onCreate();
        lm = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
            gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            Toast.makeText(getApplicationContext(), "Getting Location Via GPS",
                    Toast.LENGTH_LONG).show();
        }
        if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    this);
            networkLocation = lm
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            Toast.makeText(getApplicationContext(),
                    "Getting location Via Network", Toast.LENGTH_LONG).show();
        }
        if (gpsLocation != null) {
            Toast.makeText(
                    getApplicationContext(),
                    "GPSLOCATION: " + gpsLocation.getLatitude() + " , "
                            + gpsLocation.getLongitude(), Toast.LENGTH_LONG)
                    .show();
        }
        if (networkLocation != null) {
            Toast.makeText(
                    getApplicationContext(),
                    "NETWORKLOCATION: " + networkLocation.getLatitude() + " , "
                            + networkLocation.getLongitude(), Toast.LENGTH_LONG)
                    .show();
        }
        if (gpsLocation == null && networkLocation == null) {
            Toast.makeText(getApplicationContext(),
                    "Couldn't get user location", Toast.LENGTH_LONG).show();
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread() {
            public void run() {
                Looper.prepare();

                if (gpsLocation != null) {
                    Log.d("Usman", "GPSLOCATION: " + gpsLocation.getLatitude()
                            + " , " + gpsLocation.getLongitude());
                }
                if (networkLocation != null) {
                    Log.d("Usman",
                            "NETWORKLOCATION: " + networkLocation.getLatitude()
                                    + " , " + networkLocation.getLongitude());
                }
                if (gpsLocation == null && networkLocation == null) {
                    Log.d("Usman", "Couldn't get user lcoation");
                }
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Looper.loop();
            }
        }.start();
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        // do something with this location

        Toast.makeText(
                getApplicationContext(),
                location.getProvider() + " Location Changed:"
                        + location.getLatitude() + " , "
                        + location.getLongitude(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProviderDisabled(String arg0) {
        Toast.makeText(getApplicationContext(), arg0 + " Disabled",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(getApplicationContext(), provider + " Enabled",
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    }

}

在onCreate()方法中,gps和网络位置都为空。 谁能告诉我哪里错了

3 个答案:

答案 0 :(得分:1)

正如你所说,你甚至没有得到“通过网络获取位置”的祝酒词。所以你的执行不会进入

的if块
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

}

因此请确保您已选中

Google的位置服务 - 已检查

在您的设备设置中。

设置>位置服务> Google的位置服务和访问位置。

然后你应该从LocationManager获取位置。其余的代码看起来很好。

希望这有帮助。

Reference link

答案 1 :(得分:0)

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 1000*60*1, this);

答案 2 :(得分:0)

您需要牢记权限:

1.如果您想同时使用NETWORK_PROVIDER和GPS_PROVIDER使用许可。

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

2.如果只想使用NETWORK_PROVIDER 使用

<uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />

3.正常人可以做一个非常常见的错误。不要忘记给互联网许可

<uses-permission android:name="android.permission.INTERNET" />

4.第一个定位位置可以足够长,// locationManager.getLastKnownLocation(locationProvider)为您提供缓存位置 它也可以为空。

您可以根据特定标准请求位置:

// The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 5; // 5 minute


Criteria criteria = new Criteria();
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(false);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            String providerFine = locationManager.getBestProvider(criteria,
                    true);

            criteria.setAccuracy(Criteria.ACCURACY_COARSE);
            String providerCoarse = locationManager.getBestProvider(criteria,
                    true);

            if (providerCoarse != null) {

                locationManager.requestLocationUpdates(providerCoarse,
                        MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
                        this);
            }
            if (providerFine != null) {

                locationManager.requestLocationUpdates(providerFine,
                        MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,
                        this);
            }

获取位置后,您可以检查最佳位置修复 下面给出了以下方法:http://developer.android.com/guide/topics/location/strategies.html

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);
}