【问题标题】:Get current user location获取当前用户位置
【发布时间】:2023-03-03 08:27:23
【问题描述】:

我正在尝试获取当前用户位置,但在某些设备上它可以工作,但在某些设备上我卡在等待位置。

这是我的代码:

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

有人可以帮我看看这段代码有什么问题,并告诉我如何正确获取用户位置吗?

谢谢!

【问题讨论】:

  • 可能那些设备不支持Gps
  • @koutuk 我不认为,有问题的设备是 Nexus5
  • locationManager.getBestProvider(c, false)-> 你收到了一个禁用的提供者。

标签: java android android-location


【解决方案1】:

尝试换行

locationManager.getBestProvider(c, false)

locationManager.getBestProvider(c, true)

here 所述,“enabledOnly - 如果为 true,则仅返回当前启用的提供程序”。您可能会取回未启用的提供程序。
还有一件事,您似乎在使用 Criteria,我通常不使用它,但从查看您的代码来看,您似乎并没有用它做太多事情。我建议你再看看它。我找到了一个代码示例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

【讨论】:

    【解决方案2】:

    答案是添加这行代码:

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

    【讨论】:

      【解决方案3】:

      试试这个

      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();
          }
      }
      

      【讨论】:

        【解决方案4】:

        我认为您的代码也不是那么好和主要。有没有更好的办法。

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

        【讨论】:

          猜你喜欢
          • 2011-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-18
          • 2013-04-11
          相关资源
          最近更新 更多