java - 我怎样才能得到当前位置

标签 java android latitude-longitude android-location android-gps

我的 Android 应用程序有问题。我使用这个类:

package com.example.seadog.gps;

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;

import org.json.JSONObject;

public class GPSTracker extends Service implements LocationListener {

    private Context mContext;

    public GPSTracker() {

    }

    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 = 5000;

    protected LocationManager locationManager;

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

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

            isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {

            } else {

                this.canGetLocation = true;

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

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

        return latitude;
    }

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

        return longitude;
    }

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


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

        alertDialog.setTitle("GPS jest wyłączony");

        alertDialog.setMessage("Do używania tej aplikacji wymagany jest GPS. W tym celu przejdź do ustawień, włącz GPS a następnie uruchom ponownie.");

        alertDialog.setPositiveButton("Ustawienia", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
                System.exit(0);
            }
        });

        alertDialog.setNegativeButton("Anuluj", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                System.exit(0);
            }
        });


        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {

        int ID = GlobalConfig.ID;
        int Random = GlobalConfig.Random;

        double latitude = location.getLatitude();
        double longitude = location.getLongitude();

        try {

            JSONObject json = new JSONObject();
            json.put("ID", ID);
            json.put("Random", Random);
            json.put("latitude", latitude);
            json.put("longitude", longitude);

            GlobalConfig config = new GlobalConfig();
            config.set(json);
            //config.i(0);

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

    }

    @Override
    public void onProviderDisabled(String provider) {
        System.exit(0);
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

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

}

本类(class)摘自网络。我在 OnChangedLocation 中添加了自己的代码。当坐标发生变化时,然后在 GlobalConfig 类中创建一个具有新纬度和经度的 JSONObject。 在另一个类中有一个服务,它在后台每 5 秒向服务器发送一次数据。 我的问题是纬度和经度不正确。有时获得的值(value)是正确的,有时则不是。该位置在大约 10 分钟或几分钟内保持不变,并在一段时间后显示正确的值。 我的应用程序在后台运行。在浏览器上,我在谷歌地图上进行了预览,我的标记跳到了 map 上。我在开车时测试了它。

出了点问题。我想获得正确的纬度和经度。帮助!

最佳答案

您应该使用最后一个 Google API 来定位。首先,您像这样连接此 API:

GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(locationClientCallback)
                    .addOnConnectionFailedListener(locationClientCallback)
                    .build();

if (!(googleApiClient.isConnected() || googleApiClient.isConnecting())) {
       googleApiClient.connect();
}

现在,无论 API 是否连接,您都会在 locationClientCallback 中收到。

private class LocationClientCallback implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            if (location == null) {
                return;
            }

            // YOU HAVE YOUR POSITION

        }

        @Override
        public void onConnectionFailed(ConnectionResult arg0) {
            // CONNECTION FAILED
        }

        @Override
        public void onConnected(Bundle arg0) {
            // GOOGLE API CONNECTED 


            // MAKE A REQUEST FOR LOCATIONS
            LocationRequest request = LocationRequest.create();
            request.setSmallestDisplacement(0);
            request.setInterval(5000);
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, request, this);

        }

        @Override
        public void onConnectionSuspended(int i) {
            // CONNECTION SUSPENDED

        }


    }

并且在回调中您会收到位置和其他事件。在 onConnected 事件中,您应该向 Google API 客户端请求位置。

希望对你有帮助!!

关于java - 我怎样才能得到当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34038409/

相关文章:

c# - 经纬度列表计算中心点与实际略有不同

php - 从 Android 应用程序连接和更新 php 服务器

java - Android 不支持 Java v7+,所以我应该使用多个 catch 还是一个带有 instanceof 检查的 catch?

java - 如何实现比较器来比较名称?

android - 使用 declare styleable 设置自定义组件输入类型

java - TCP 套接字无法接收数据包

geocoding - 使用 google geocoding api jquery 从经度和纬度获取城市名称

java - 我的 Java 程序没有改变变量的值

java - 获取对象的大小

android - 如何发送崩溃报告作为Android应用程序的Alpha测试仪?