2014-12-16 9 views
0

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

Вот мой код:

private final LocationListener mLocationListener = new LocationListener() { 
     @Override 
     public void onLocationChanged(final Location location) { 
      // TODO 
      Log.v("--", "get address 121"); 
      Main.this.location = location; 
      getAddress(); 
      locationManager.removeUpdates(mLocationListener); 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
      // TODO Auto-generated method stub 

     } 

     @Override 
     public void onProviderEnabled(String provider) { 
      // TODO Auto-generated method stub 
      Log.v("--", "provider enabled"); 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
      // TODO Auto-generated method stub 
      Log.v("--", "provider disabled"); 
     } 
    }; 

    public void putExtra() { 
     Intent intent = new Intent(this, Settings.class); 
     intent.putExtra("timesobj", times); 
     startActivity(intent); 
    } 

    /** 
    * Get current/last known location and display city, country name and update 
    * calculations 
    * */ 
    public void getAddress() { 
     Log.v("--", "get address 1"); 
     boolean isGPSProviderEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 
     boolean network_enabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     Log.v("--", "get address 31 " + isGPSProviderEnabled + " gps - " 
       + isConnectedToNetwork()); 

     if (isGPSProviderEnabled || network_enabled) { 
      Log.v("--", "get address 2"); 
      Criteria c = new Criteria(); 
      Log.v("--", "provider " + locationManager.getBestProvider(c, true)); 
      location = locationManager.getLastKnownLocation(locationManager 
        .getBestProvider(c, false)); 

      if (location == null) { 
       Log.v("--", "get address 6"); 
       locationManager.requestLocationUpdates(
         locationManager.getBestProvider(c, false), 1000, 100, 
         mLocationListener); 
      } else { 
       Log.v("--", "get address 3"); 
       if (isConnectedToNetwork()) { 
        new AsyncTask<Void, Void, Void>() { 
         protected Void doInBackground(Void... params) { 
          try { 
           com.myapp.utils.Geocoder geocoder = new com.myapp.utils.Geocoder(
             Main.this); 
           GeocoderModel geocoderModel = geocoder 
             .getFromLocation(
               location.getLatitude(), 
               location.getLongitude(), 5); 
           city = geocoderModel.getCity(); 
           country = geocoderModel.getCountry(); 
           prefs.edit().putString(Constants.CITY, city) 
             .apply(); 
           Log.v("--", "get address 4"); 
          } catch (IOException e) { 
           Log.v("--", "get address 11"); 
           e.printStackTrace(); 
          } catch (LimitExceededException e) { 
           Log.v("--", "get address 12"); 
           e.printStackTrace(); 
          } 
          return null; 
         }; 

         protected void onPostExecute(Void result) { 
          prefs.edit().putString(Constants.COUNTRY, country) 
            .apply(); 
          prefs.edit().putString(Constants.CITY, city) 
            .apply(); 
          populateList(location); 
         }; 
        }.execute(); 
       } else { 
        city = prefs.getString(Constants.CITY, 
          getString(R.string.app_name)); 
        Log.v("--", "get address 33 " + location.getLatitude()); 
        populateList(location); 
       } 
      } 
     } else { 
      Log.v("--", "get address 5"); 
      startGpsEnableDialog(); 
     } 
    } 

и вот журнала, что у меня есть:

V/--  (5498): get address 1 
V/--  (5498): get address 31 true gps - true 
V/--  (5498): get address 2 
V/--  (5498): provider gp 
V/--  (5498): get address 6 

Может кто-то поможет мне, что может быть неправильно в этом коде, и скажите мне, как я могу правильно определить местоположение пользователя?

Спасибо!

+0

вероятно эти устройства не поддерживаются Gps – koutuk

+0

@koutuk я не разжижаю, проблемное устройство Nexus5 –

+0

или это из-за недельным датчик GPS на этих устройствах, а также я хочу отметить, что GPS не работает в все ситуации, такие как внутренние позиции –

ответ

1

Ответ добавлял эту строку кода:

locationManager.requestSingleUpdate(locationManager.getBestProvider(c, true), mLocationListener, Looper.myLooper()); 
1

Попробуйте изменить линию

locationManager.getBestProvider(c, false) 

в

locationManager.getBestProvider(c, true) 

Как заявил here, "enabledOnly - если это правда, то только поставщик, который в данный момент включен возвращается". Вы можете вернуть провайдера, который не включен.
Еще одна вещь, вы, кажется, используете критерии, я обычно не использую ее, но, глядя на ваш код, похоже, что вы мало что с этим делаете. Я предлагаю вам еще раз взглянуть на это. Я нашел образец кода here, который может вам помочь.

private void startLocationStuff(){ 
    locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    locListener=new MyLocationListener(); 
    final Criteria criteria=new Criteria(); 
    criteria.setAccuracy(Criteria.ACCURACY_FINE); 
    criteria.setAltitudeRequired(false); 
    criteria.setBearingRequired(false); 
    criteria.setCostAllowed(true); 
    criteria.setPowerRequirement(Criteria.POWER_LOW); 
    bestProvider=locManager.getBestProvider(criteria,true); 
} 

Вы можете рассмотреть вопрос об использовании менеджера Местоположение без критериев, как this.

0

попробовать этот

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; 

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

// The minimum time between 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 (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       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(); 
        } 
       } 
      } 
      // 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(); 
    } 

    return location; 
} 

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

/** 
* 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 Settings"); 

    // Setting Dialog Message 
    alertDialog 
      .setMessage("GPS is not enabled. You want to go to the 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) { 
} 

@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; 
} 

} 

внутри MainActivity.java метода вызова

public void getCurrentLatLng() { 

    GPSTracker gps = new GPSTracker(SignInActivity.this); 
    // check if GPS enabled 
    if (gps.isGPSEnabled) { 
     double latitude = gps.getLatitude(); 
     double longitude = gps.getLongitude(); 
     LatLng currentLatLng = new LatLng(latitude, longitude); 
     System.out.println(currentLatLng); 
    } else { 
     gps.showSettingsAlert(); 
    } 
} 
0

I подумайте, y наш код не так уж и хорош и главный. Есть ли способ лучше .

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 android.support.v7.app.AlertDialog; 

import android.util.Log; 

/** 
* Created by moodless3 2017 
*/ 

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; 

    // 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 = 1000; // 1000 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2; // 2 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 (!isGPSEnabled && !isNetworkEnabled) { 

       // No network provider is enabled 

      } else { 

       this.canGetLocation = true; 

       if (isNetworkEnabled) { 

        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(); 
         } 
        } 
       } 
       // If GPS enabled, get latitude/longitude 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(); 
     } 

     return location; 
    } 


    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app. 
    * */ 
    public void stopUsingGPS(){ 

     if(locationManager != null) { 

      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 


    /** 
    * 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/Wi-Fi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 


    /** 
    * Function to show settings alert dialog. 
    * On pressing the Settings button it will launch 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 the 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 the 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) { 
    } 


    @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; 
    } 
} 
Смежные вопросы