java - 问:Android GPS 位置

标签 java android gps

我正在尝试访问我设备的 GPS 位置,这样我就可以使用它来加载用户坐标上的 Google map 。我遵循了各种指南,但我似乎没有获得任何正确的值。

应用不会崩溃,它只是显示一个零

这是我的 map Activity 的代码:

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

我还在 list 中包含了必要的代码:

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

非常感谢帮助

最佳答案

请勿使用 GPSTracker!!!!亲爱的上帝,这段代码不会死。这是可怕的、糟糕的、可怕的代码。我在 http://gabesechansoftware.com/location-tracking/ 有一篇博文显示代码存在缺陷的十几种不同方式。我还有一个更好的实现。该代码是由不完全了解位置跟踪的人编写的,并且做出了很多错误的假设。

如果我被允许从这个网站上删除一门类(class),那将是所有提及的类(class)。它只是非常幼稚的代码。

关于java - 问:Android GPS 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423025/

相关文章:

java - 无法引用 Thymeleaf 中的迭代变量

java - Java 8中使用一个Stream执行多个get操作并保存结果

java - 安全异常 : Binder invocation to an incorrect interface on signed APK

android - 点击外部edittext失去焦点

android - 反序列化时出现 Gson 异常(无参数构造函数不存在)

java - 为什么在java中加载JNI是在静态初始化程序中完成的?

android - 等到 GPS 启用后再获取 FusedLocationAPI 中的纬度和经度值

android - 在 Android 中启用 GPS 设置

android - 当针对目标 API 级别 29 进行编译时,能否在 Android API 级别 < 24 上访问 NMEA?

android - 如何在 java 中编写用于添加覆盖 List<object> 的代码?