Java Android位置类的问题

Java Android位置类的问题,java,android,google-maps,location,Java,Android,Google Maps,Location,我正在尝试获取当前位置,但我遇到以下问题: Location location = locationManager.getLastKnownLocation(locationManager .getBestProvider(criteria, false)); at import android.annotation.SystemApi; "Cannot resolve symbol SystemApi" at private static ThreadLocal&

我正在尝试获取当前位置,但我遇到以下问题:

Location location = locationManager.getLastKnownLocation(locationManager
            .getBestProvider(criteria, false));
at import android.annotation.SystemApi; "Cannot resolve symbol SystemApi"

at  private static ThreadLocal<BearingDistanceCache> sBearingDistanceCache
            = new ThreadLocal<BearingDistanceCache>() "Cannot acces android.location.Location.BearingDistanceCache"
在此调用之后,location始终为null。如果我查看location类,我会发现以下问题:

Location location = locationManager.getLastKnownLocation(locationManager
            .getBestProvider(criteria, false));
at import android.annotation.SystemApi; "Cannot resolve symbol SystemApi"

at  private static ThreadLocal<BearingDistanceCache> sBearingDistanceCache
            = new ThreadLocal<BearingDistanceCache>() "Cannot acces android.location.Location.BearingDistanceCache"
导入android.annotation.SystemApi;“无法解析符号SystemApi”
在专用静态线程本地sBearingDistanceCache
=new ThreadLocal()“无法访问android.location.location.BearingDistanceCache”
此处描述了此位置类别:

试图使缓存无效/重新启动缓存,但仍无法工作。 下一步我应该试试什么

import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.GpsSatellite;
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 android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.LocationSource;


public class GPSTrack extends Service implements LocationListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationSource{

private GoogleApiClient mGoogleApiClient;
private OnLocationChangedListener mMapLocationListener = null;
private static final LocationRequest REQUEST = LocationRequest.create()
        .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

 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 = 1; //1 meter ; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000; //1 sec,  * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTrack(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) {
                    try {
                        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();
                            }
                        }
                    }catch (SecurityException se){

                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        try{
                            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 (SecurityException se){

                        }

                    }
                }
            }

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

        return location;
    }




@Override
public void onConnected(Bundle connectionHint) {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient,
            REQUEST,
            (com.google.android.gms.location.LocationListener) this);  // LocationListener
}


@Override
public void onConnectionSuspended(int cause) {
    // Do nothing
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    // Do nothing
}

@Override
public void activate(OnLocationChangedListener onLocationChangedListener) {
    mMapLocationListener = onLocationChangedListener;
}

@Override
public void deactivate() {
    mMapLocationListener = null;
}

    public int onGpsStatusChanged() {
        int satellites = 0;
        int satellitesInFix = 0;
        int timetofix = locationManager.getGpsStatus(null).getTimeToFirstFix();
        for (GpsSatellite sat : locationManager.getGpsStatus(null).getSatellites()) {
            if(sat.usedInFix()) {
                satellitesInFix++;              
            }
            satellites++;
        }

        return satellites;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            try{
                locationManager.removeUpdates(GPSTrack.this);
            }catch (SecurityException se){

            }

        }
    }

    /**
     * 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) {
        if (mMapLocationListener != null) {
            mMapLocationListener.onLocationChanged(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;
    }

}
获取位置

GPSTrack gpsTrack = new GPSTrack(context);
if(gpsTrack.canGetLocation()){
    Location location = gpstracker.getLocation();
    double lat = location.getLatitude();
    double lang = location.getLongitude();
}
AndroiManifeast.xml

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


位置已激活,我可以使用mMap.setMyLocationEnabled(true)在地图上看到我的位置;问题是我无法检索lat和long,我应该如何在新的GPSTrack(context)中实例化上下文?YourActivityName.This欢迎您!!!哦,没有一本androidhive最差的教程<代码>服务不需要
上下文
因为它是一个
上下文
服务
需要一个无参数构造函数,
服务
不能使用
新的
操作符初始化<代码>捕获异常应该有一些日志。。。等等等等等等。。。这段代码是噩梦很明显,下一次某个可怜的家伙会找到你的答案,可能会犯下他一生中最严重的错误。。。复制粘贴并使用它。。。