2017-04-20 25 views
-3

問題,我試圖讓我的當前位置,但我有以下問題:與Android位置類

Location location = locationManager.getLastKnownLocation(locationManager 
      .getBestProvider(criteria, false)); 
這個電話後

,位置始終null.If我看看在Location類,我看到以下問題:

at import android.annotation.SystemApi; "Cannot resolve symbol SystemApi" 

at private static ThreadLocal<BearingDistanceCache> sBearingDistanceCache 
      = new ThreadLocal<BearingDistanceCache>() "Cannot acces android.location.Location.BearingDistanceCache" 

這個位置類描述如下:https://developer.android.com/reference/android/location/Location.html

嘗試無效/重啓緩存,但它仍然是行不通的。 接下來我應該嘗試什麼?

+0

位置被激活,我可以看到使用mMap.setMyLocationEnabled在地圖上我的位置(真) ;問題是我無法檢索經緯度 – Miru

回答

-2
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" /> 
+0

我應該如何在新的GPSTrack(上下文)中實例化上下文; ? – Miru

+0

YourActivityName.this – MinnuKaAnae

+0

謝謝,它的工作! – Miru