2014-09-12 4 views
-1

Я пытаюсь получить текущее местоположение, используя либо GPS, либо Network Provider. Мое устройство GPS включено, но я не получаю Latitude и Longitude.Невозможно получить GPS Локатор и долгота местоположения текущего местоположения Android

Может кто поможет решить проблему:

GpsTracker.java:

public class GpsTracker extends Service implements LocationListener { 

     private final Context mContext; 
     // flag for GPS Status 
     boolean isGPSEnabled = false; 
     // flag for network status 
     boolean isNetworkEnabled = false; 
     boolean canGetLocation = false; 
     Location location; 
     public double latitude; 
     public double longitude; 

     // The minimum distance to change updates in metters 
     private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 
     // metters 

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

        // Declaring a Location Manager 
        protected LocationManager locationManager; 

        public GpsTracker(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 Network Provider Enabled get lat/long using GPS Services 
           if (isNetworkEnabled) { 
            if (location == null) { 
             locationManager.requestLocationUpdates(
               LocationManager.NETWORK_PROVIDER, 
               MIN_TIME_BW_UPDATES, 
               MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 


             if (locationManager != null) { 
              location = locationManager 
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
              updateGPSCoordinates(); 
             } 
            } 
           } 

           // if GPS Enabled get lat/long using GPS Services 
           if (isGPSEnabled) { 
            if (location == null) { 
             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 (Exception e) { 
          // e.printStackTrace(); 
          Log.e("Error : Location", 
            "Impossible to connect to LocationManager", e); 
         } 

         return location; 
        } 

        public void updateGPSCoordinates() { 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 

        public double getLatitude() { 
         if (location != null) { 
          latitude = location.getLatitude(); 
         } 

         return latitude; 
        } 

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

         return longitude; 
        } 

       } 

Service.Java

 public class WifiScaningService extends IntentService { 

     GpsTracker gpsTracker; 
     double latitude; 
      double longitude; 
     public WifiScaningService() { 
       super("WifiScaningService"); 

      } 

      @Override 
      public IBinder onBind(Intent intent) {  
       // TODO: Return the communication channel to the service. 
       throw new UnsupportedOperationException("Not yet implemented"); 
      } 

      @Override 
      public void onCreate() { 
       Log.e("service call","service call");  

      } 


      @Override 
      protected void onHandleIntent(Intent intent) { 

      } 
      @Override 


      public int onStartCommand(Intent intent, int flags, int startId) { 
        Log.i("LocalService", "Received start id " + startId + ": " + intent); 

        gpsTracker = new GpsTracker(this); 
        String stringLatitude = String.valueOf(gpsTracker.latitude);  
        latitude = Double.parseDouble(stringLatitude); 
        Log.e("Latitude",stringLatitude);  
        String stringLongitude = String.valueOf(gpsTracker.longitude); 
        longitude = Double.parseDouble(stringLongitude); 
        Log.e("Longitude",stringLongitude); 

       return START_STICKY; 
      } 
    } 

Я включил необходимые разрешения в AndroidManifest.xml файле. Требуется для отображения текущего местоположения.

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

Содержит ли ваш код? Я не вижу метода onLocationChanged(), который должен реализовать ваш GpsTracker, поскольку он реализует интерфейс LocationListener. – Stefan

+0

Да, проблемы с компиляцией и onLocationChanged() не удаляются в этом коде – Rajesh

+0

Так как это метод, который вызывается, если доступна новая позиция, вы должны его опубликовать. getLastKnownLocation может дать вам очень старое местоположение, и оно может быть нулевым, что может быть причиной, по которой вы получаете 0 в качестве результата. – Stefan

ответ

0

Я решаемые путем обмена позиции и методы.

Первое приложение пытается получить местоположение с использованием GPS, если GPS не включен, а затем использует метод сетевого провайдера.

public class GpsTracker extends Service implements LocationListener { 

private final Context mContext; 

// flag for GPS Status 
boolean isGPSEnabled = false; 
// flag for network status 
boolean isNetworkEnabled = false; 
boolean canGetLocation = false; 
Location location; 
public double latitude; 
public double longitude; 

// The minimum distance to change updates in metters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 
// metters 

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

// Declaring a Location Manager 
protected LocationManager locationManager; 

public GpsTracker(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 GPS Enabled get lat/long using GPS Services 
     if (isGPSEnabled) { 
      if (location == null) { 
       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(); 
        } 
       } 
      } 
      // if Network Provider Enabled get lat/long using GPS Services 
      if (isNetworkEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 


        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         updateGPSCoordinates(); 
        } 
       } 
      } 


     } 

    } catch (Exception e) { 
     // e.printStackTrace(); 
     Log.e("Error : Location", 
       "Impossible to connect to LocationManager", e); 
    } 

    return location; 
} 

public void updateGPSCoordinates() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
    } 
} 

public double getLatitude() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
    } 

    return latitude; 
} 

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

    return longitude; 
} 

} 
2

MainActivity:

import android.location.Address; 
import android.location.Location; 
import com.example.havadurumumenu.MyLocationManager.LocationHandler; 

public class MainActivityextends Activity implements LocationHandler{ 

    public MyLocationManager locationManager; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     button1 = (Button) findViewById(R.id.button1); 
     button1.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       currentLocation();    
      } 
     }); 
    } 

    public void currentLocation(){ 

     locationManager = new MyLocationManager(); 
     locationManager.setHandler(this); 

     boolean isBegin = locationManager.checkProvidersAndStart(getApplicationContext()); 
     if(isBegin){ 
      //if at least one of the location providers are on it comes into this part. 
     }else{ 
      //if none of the location providers are on it comes into this part. 
     } 

    } 

    @Override 
    public void locationFound(Location location) { 
     Log.d("LocationFound", ""+location); 

     //you can reach your Location here 
     //double latitude = location.getLatitude(); 
     //double longtitude = location.getLongitude(); 

     locationManager.removeUpdates(); 
    } 

    @Override 
    public void locationTimeOut() { 
     locationManager.removeUpdates(); 

     //you can set a timeout in MyLocationManager class 

     txt.setText("Unable to locate. Check your phone's location settings"); 
    } 

MyLocationManager:

import java.io.IOException; 
import java.util.List; 
import java.util.Locale; 

import android.annotation.SuppressLint; 
import android.content.Context; 
import android.location.Address; 
import android.location.Geocoder; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 

/*---------- Listener class to get coordinates ------------- */ 
public class MyLocationManager implements LocationListener { 

    public LocationManager locationManager; 
    public LocationHandler handler; 
    private boolean isLocationFound = false; 

    public MyLocationManager() {} 

    public LocationHandler getHandler() { 
     return handler; 
    } 

    public void setHandler(LocationHandler handler) { 
     this.handler = handler; 
    } 
    @SuppressLint("HandlerLeak") 
    public boolean checkProvidersAndStart(Context context){ 
     boolean isBegin = false; 

     Handler stopHandler = new Handler(){ 
      public void handleMessage(Message msg){ 
       if (!isLocationFound) { 
         handler.locationTimeOut(); 
       } 
      } 
     }; 
     stopHandler.sendMessageDelayed(new Message(), 15000); 

     locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE); 

     if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1000, this); 
      isBegin = true; 
     } 
     if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){ 
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1000, this); 
      isBegin = true; 
     } 
     return isBegin;  
    } 

    public void removeUpdates(){ 
     locationManager.removeUpdates(this); 
    } 
    /** 
    * To get city name from coordinates 
    * @param location is the Location object 
    * @return city name 
    */ 
    public String findCity(Location location){ 
     /*------- To get city name from coordinates -------- */ 
     String cityName = null; 
     Geocoder gcd = new Geocoder(AppController.getInstance(), Locale.getDefault()); 
     List<Address> addresses; 
     try { 
      addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1); 
      cityName = addresses.get(0).getLocality(); 
     } 
     catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return cityName; 
    } 

    @Override 
    public void onLocationChanged(Location loc) { 
     isLocationFound = true; 
     handler.locationFound(loc); 
    } 

    @Override 
    public void onProviderDisabled(String provider) {} 

    @Override 
    public void onProviderEnabled(String provider) {} 

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

    public interface LocationHandler{ 
     public void locationFound(Location location); 
     public void locationTimeOut(); 
    } 
} 

Кроме того, добавьте все разрешения ниже в вашем Manifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.INTERNET" /> 
Смежные вопросы