安卓GPS定位

4

我正在尝试获取我的设备的GPS位置,以便可以使用该位置来加载用户坐标的Google地图。我已经按照各种指南进行了操作,但是似乎没有获得任何正确的值。

应用程序不会崩溃,只是显示为零

这是我的地图活动的代码:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class Maps extends ActionBarActivity {

Button btnLocation;
GPSTracker gps;


//private GoogleMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Hide action bar before Activity load
    getSupportActionBar().hide();
    setContentView(R.layout.activity_maps);


    btnLocation = (Button) findViewById(R.id.btnLocation);

    btnLocation.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            gps = new GPSTracker(Maps.this);

            if(gps.canGetLocation()){
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();

                Toast.makeText(getApplicationContext(),
                        "Your location is -\nLat: " + latitude +
                        "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            } else {
                gps.showSettingsAlert();
            }
        }
    });

以下是我编写的代码,旨在获取位置信息。
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;

public class GPSTracker extends Service implements LocationListener {

    private final Context context;
//Flags for network/gps status
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;

Location location;

double latitude;
double longitude;

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;

public LocationManager locationManager;

public GPSTracker(Context context) {
    this.context = context;
    getLocation();
}

public Location getLocation(){
    try {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            //For use over networks
            if (isNetworkEnabled) {

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

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (location != null) {
                      latitude = location.getLatitude();
                      longitude = location.getLongitude();
                    }
                }
            }
            //For use over GPS
            if (isGPSEnabled) {
                if(location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

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



public void stopUsingGPS() {
    if(locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    } else {
        getLocation();
    }
    return latitude;
}

public double getLongitude() {
    if (location != null){
        longitude = location.getLongitude();
    } else {
        getLocation();
    }
    return longitude;
}



public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

    alertDialog.setTitle("GPS is being set");

    alertDialog.setMessage("GPS is not enabled. Go to settings.");

    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);

        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}


public boolean canGetLocation() {
    return this.canGetLocation;
}

我还将必要的代码添加到清单中: ```html

我还将必要的代码添加到清单中:

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

非常感谢您的帮助

1个回答

4
请勿使用GPSTracker!这段代码非常糟糕、糟心和糟糕透顶。我在http://gabesechansoftware.com/location-tracking/上发布了博客文章,展示了此代码存在的十几种缺陷。同时,在那里也有更好的实现方法。这段代码是由一个没有完全理解位置跟踪的人编写的,并且做出了很多错误的假设。
如果我被允许从这个网站中删除一个类,那么一定是所有提到它的类。这只是极其幼稚的代码。

你很棒,伙计。 - Yauraw Gadav
感谢您的回复。在阅读了这篇文章后,我发现很多人都对这段代码进行了抱怨,但不幸的是,我对Java还比较陌生。虽然我想让它正常工作,但我认为我会尝试另一种实现方式。 - Jordan
@Gabe我看过你的代码,但是你怎么实现它,没有样例来使用你的代码。能否提供一个样例呢? - Djama

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