我如何获取当前位置

时间:2015-12-02 08:52:48

标签: 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;
    }

}

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

出了点问题。我想得到正确的纬度和经度。救命啊!

1 个答案:

答案 0 :(得分:2)

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

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

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

现在,在您的locationClientCallback中,如果API已连接,则会收到。

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客户端请求位置。

希望它可以帮到你!!