经纬度返回0,0。

3

我正在尝试创建一个显示我的当前位置的应用程序,我拥有所有必要的权限,我还有另一个名为GPS跟踪器的类来获取我的GPS位置。

这是我的代码:

GPSTracker gpsTracker = new GPSTracker(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude = gpsTracker.latitude;
longitude = gpsTracker.longitude;
LatLng latLng = new  LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(18));

以下是 GPSTracker 类:

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;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// 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

// 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);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // 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);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * 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
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        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("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@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 arg0) {
    return null;
}

}


在设备上运行你的应用程序,模拟器总是显示0,0。 - prabhakaran
你是在真实设备上尝试吗? - Lal
是的,我正在尝试在我的平板电脑上:S 问题是它以前运行得很好。我关闭了笔记本电脑,第二天早上打开它,它开始给出0,0,无法弄清原因:S - ak52
它之所以不起作用有两个原因。第一个是你还没有GPS锁定。第二个是因为这门课太糟糕了,我们每周都会收到多个关于它的问题。请看下面我的答案。 - Gabe Sechan
3个回答

5
请勿使用GPS跟踪器类。它有太多的问题,我今晚写了一篇长篇博客文章: 请参见http://gabesechansoftware.com/location-tracking/
以下是它的问题:
1)它不能追踪GPS。有时会跟踪网络位置
2)canGetLocation函数是有问题的。它在没有位置之前就返回true 3)它非常低效,强制你进行轮询。
4)它不区分陈旧数据和新鲜数据-也不让你这样做
我可以继续写下去,但我已经在今晚写了。我在我的博客上写了一个更好的GPS跟踪库。在这里为SO使用重复。

LocationTracker.java

package com.gabesechan.android.reusable.location;

import android.location.Location;

public interface LocationTracker {
    public interface LocationUpdateListener{
        public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
    }

    public void start();
    public void start(LocationUpdateListener update);

    public void stop();

    public boolean hasLocation();

    public boolean hasPossiblyStaleLocation();

    public Location getLocation();

    public Location getPossiblyStaleLocation();

}

ProviderLocationTracker.java

package com.gabesechan.android.reusable.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

public class ProviderLocationTracker implements LocationListener, LocationTracker {

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

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

    private LocationManager lm;

    public enum ProviderType{
        NETWORK,
        GPS
    };    
    private String provider;

    private Location lastLocation;
    private long lastTime;

    private boolean isRunning;

    private LocationUpdateListener listener;

    public ProviderLocationTracker(Context context, ProviderType type) {
        lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
        if(type == ProviderType.NETWORK){
            provider = LocationManager.NETWORK_PROVIDER;
        }
        else{
            provider = LocationManager.GPS_PROVIDER;
        }
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //The provider is on, so start getting updates.  Update current location
        isRunning = true;
        lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
        lastLocation = null;
        lastTime = 0;
        return;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;

    }


    public void stop(){
        if(isRunning){
            lm.removeUpdates(this);
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        if(lastLocation == null){
            return false;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return false; //stale
        }
        return true;
    }

    public boolean hasPossiblyStaleLocation(){
        if(lastLocation != null){
            return true;
        }
        return lm.getLastKnownLocation(provider)!= null;
    }

    public Location getLocation(){
        if(lastLocation == null){
            return null;
        }
        if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
            return null; //stale
        }
        return lastLocation;
    }

    public Location getPossiblyStaleLocation(){
        if(lastLocation != null){
            return lastLocation;
        }
        return lm.getLastKnownLocation(provider);
    }

    public void onLocationChanged(Location newLoc) {
        long now = System.currentTimeMillis();
        if(listener != null){
            listener.onUpdate(lastLocation, lastTime, newLoc, now);
        }
        lastLocation = newLoc;
        lastTime = now;
    }

    public void onProviderDisabled(String arg0) {

    }

    public void onProviderEnabled(String arg0) {

    }

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




}

FallbackLocationTracker.java

package com.gabesechan.android.reusable.location;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;

public class FallbackLocationTracker  implements LocationTracker, LocationTracker.LocationUpdateListener {


    private boolean isRunning;

    private ProviderLocationTracker gps;
    private ProviderLocationTracker net;

    private LocationUpdateListener listener;

    Location lastLoc;
    long lastTime;

    public FallbackLocationTracker(Context context, ProviderLocationTracker.ProviderType type) {
        gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
        net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
    }

    public void start(){
        if(isRunning){
            //Already running, do nothing
            return;
        }

        //Start both
        gps.start(this);
        net.start(this);
        isRunning = true;
    }

    public void start(LocationUpdateListener update) {
        start();
        listener = update;
    }


    public void stop(){
        if(isRunning){
            gps.stop();
            net.stop();
            isRunning = false;
            listener = null;
        }
    }

    public boolean hasLocation(){
        //If either has a location, use it
        return gps.hasLocation() || net.hasLocation();
    }

    public boolean hasPossiblyStaleLocation(){
        //If either has a location, use it
        return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
    }

    public Location getLocation(){
        Location ret = gps.getLocation();
        if(ret == null){
            ret = net.getLocation();
        }
        return ret;
    }

    public Location getPossiblyStaleLocation(){
        Location ret = gps.getPossiblyStaleLocation();
        if(ret == null){
            ret = net.getPossiblyStaleLocation();
        }
        return ret;
    }

    public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
        boolean update = false;

        //We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
        if(lastLoc == null){
            update = true;
        }
        else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
            update = true;
        }
        else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
            update = true;
        }
        else if (newTime - lastTime > 5 * 60 * 1000){
            update = true;
        }

        if(update){
            lastLoc = newLoc;
            lastTime = newTime;
            if(listener != null){
                listener.onUpdate(lastLoc, lastTime, newLoc, newTime);                  
            }
        }

    }


}

接口定义了一个通用的位置跟踪器,因此您可以在它们之间切换。ProviderLocationTracker将允许您根据传递给其构造函数的参数通过GPS或网络进行跟踪。FallbackLocationTracker将通过两者进行跟踪,仅提供当前可用的最准确信息,但如果GPS未准备好,则会回退到网络。

嘿,@Gabe Sechan,如何使用它? - Faisal Memon
@Gabe Sechan,我应该从哪里获取带有字符串s的_latitude_和_longitude_? - Rick
@Gabe Sechan,我尝试使用您的代码,但是在ProviderLocationTracker.java中出现错误“lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);”,需要权限。我写了“ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)”,但在“this”参数中出现了错误。请帮忙!谢谢! - Roman
@Gabe Sechan,您能否提供您的类实现的代码或任何演示? - Rahul

0
使用这段代码,并从“implements LocationListener”实现您的活动。
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,   // 3 sec
        5, this);
  boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
  if(!isGPS)
    {
        showSettingsAlert();
        GPS_imageview.setBackgroundResource(R.drawable.gpsnonfix);
        //Toast.makeText(getApplicationContext(), "Please Start GPS to get more Accurate location", Toast.LENGTH_SHORT) .show();
    }

并使用以下内容

@Override
public void onLocationChanged(Location location) {



    int a=location.getExtras().getInt("satellites") ;





    if(a>4)
    {



        String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
    //  Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
        Double lat=location.getLatitude();
        Double lan=location.getLongitude();


    }else{

    }




    String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
    Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}

@Override
public void onProviderDisabled(String provider) {

    /******** Called when User off Gps *********/

   Latitude="0.0";
        Longitude="0.0";
    Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}

@Override
public void onProviderEnabled(String provider) {

    /******** Called when User on Gps  *********/

    Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

这段代码获取卫星数量。如果卫星数量大于4,则获得正确的结果...结果的准确性很高...


0
当您启动应用程序时,您的GPS可能尚未建立连接,并为您提供默认位置,例如0,0。如果您的手机在稍后的时间点找到其坐标,则应用程序无法检测到这一点。
此行:
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);

说明每当您的手机发现位置变化时,将调用“OnLocationChanged”方法(在调用该行代码的对象中)。 就我所见,您尚未实现此方法。

我建议进行以下更改。 将第三行更改为: lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,gpsTracker);

因此,它使用您的gpsTracker的onLocationChanged方法的实现。 现在,实现已经定义但尚未实现的GPSTracker类的OnLocationChanged方法:

@Override
public void onLocationChanged(Location location) {
     //This method is triggered every time your location changes. 
     //The 'location' argument can be used to access the current location.
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接