【问题标题】:How to get the current location latitude and longitude in android如何在android中获取当前位置的经纬度
【发布时间】:2013-07-05 08:18:38
【问题描述】:

在我的应用程序中,我在应用程序打开时获取当前位置的纬度和经度,但在应用程序关闭时获取。

我正在使用 Service 类在我的应用程序中获取当前位置的纬度和经度。

请告诉我如何在应用程序关闭的情况下获取当前位置的经纬度

【问题讨论】:

标签: android android-service android-location


【解决方案1】:

几个月前,我创建了 GPSTracker 库来帮助我获取 GPS 位置。如果您需要查看 GPSTracker > getLocation

Demo

AndroidManifest.xml

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

活动

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textview;

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

        // check if GPS enabled
        GPSTracker gpsTracker = new GPSTracker(this);

        if (gpsTracker.getIsGPSTrackingEnabled())
        {
            String stringLatitude = String.valueOf(gpsTracker.latitude);
            textview = (TextView)findViewById(R.id.fieldLatitude);
            textview.setText(stringLatitude);

            String stringLongitude = String.valueOf(gpsTracker.longitude);
            textview = (TextView)findViewById(R.id.fieldLongitude);
            textview.setText(stringLongitude);

            String country = gpsTracker.getCountryName(this);
            textview = (TextView)findViewById(R.id.fieldCountry);
            textview.setText(country);

            String city = gpsTracker.getLocality(this);
            textview = (TextView)findViewById(R.id.fieldCity);
            textview.setText(city);

            String postalCode = gpsTracker.getPostalCode(this);
            textview = (TextView)findViewById(R.id.fieldPostalCode);
            textview.setText(postalCode);

            String addressLine = gpsTracker.getAddressLine(this);
            textview = (TextView)findViewById(R.id.fieldAddressLine);
            textview.setText(addressLine);
        }
        else
        {
            // can't get location
            // GPS or Network is not enabled
            // Ask user to enable GPS/network in settings
            gpsTracker.showSettingsAlert();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.varna_lab_geo_locations, menu);
        return true;
    }
}

GPS 追踪器

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

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.IBinder;
import android.provider.Settings;
import android.util.Log;

/**
 * Create this Class from tutorial : 
 * http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial
 * 
 * For Geocoder read this : http://stackoverflow.com/questions/472313/android-reverse-geocoding-getfromlocation
 * 
 */

public class GPSTracker extends Service implements LocationListener {

    // Get Class Name
    private static String TAG = GPSTracker.class.getName();

    private final Context mContext;

    // flag for GPS Status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS Tracking is enabled 
    boolean isGPSTrackingEnabled = false;

    Location location;
    double latitude;
    double longitude;

    // How many Geocoder should return our GPSTracker
    int geocoderMaxResults = 1;

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

    // Store LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER information
    private String provider_info;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    /**
     * Try to get my current location by GPS or Network Provider
     */
    public void 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);

            // Try to get location if you GPS Service is enabled
            if (isGPSEnabled) {
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use GPS Service");

                /*
                 * This provider determines location using
                 * satellites. Depending on conditions, this provider may take a while to return
                 * a location fix.
                 */

                provider_info = LocationManager.GPS_PROVIDER;

            } else if (isNetworkEnabled) { // Try to get location if you Network Service is enabled
                this.isGPSTrackingEnabled = true;

                Log.d(TAG, "Application use Network State to get GPS coordinates");

                /*
                 * This provider determines location based on
                 * availability of cell tower and WiFi access points. Results are retrieved
                 * by means of a network lookup.
                 */
                provider_info = LocationManager.NETWORK_PROVIDER;

            } 

            // Application can use GPS or Network Provider
            if (!provider_info.isEmpty()) {
                locationManager.requestLocationUpdates(
                    provider_info,
                    MIN_TIME_BW_UPDATES,
                    MIN_DISTANCE_CHANGE_FOR_UPDATES, 
                    this
                );

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(provider_info);
                    updateGPSCoordinates();
                }
            }
        }
        catch (Exception e)
        {
            //e.printStackTrace();
            Log.e(TAG, "Impossible to connect to LocationManager", e);
        }
    }

    /**
     * Update GPSTracker latitude and longitude
     */
    public void updateGPSCoordinates() {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }

    /**
     * GPSTracker latitude getter and setter
     * @return latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        return latitude;
    }

    /**
     * GPSTracker longitude getter and setter
     * @return
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        return longitude;
    }

    /**
     * GPSTracker isGPSTrackingEnabled getter.
     * Check GPS/wifi is enabled
     */
    public boolean getIsGPSTrackingEnabled() {

        return this.isGPSTrackingEnabled;
    }

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

    /**
     * Function to show settings alert dialog
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        //Setting Dialog Title
        alertDialog.setTitle(R.string.GPSAlertDialogTitle);

        //Setting Dialog Message
        alertDialog.setMessage(R.string.GPSAlertDialogMessage);

        //On Pressing Setting button
        alertDialog.setPositiveButton(R.string.action_settings, new DialogInterface.OnClickListener() {

            @Override
            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(R.string.cancel, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) 
            {
                dialog.cancel();
            }
        });

        alertDialog.show();
    }

    /**
     * Get list of address by latitude and longitude
     * @return null or List<Address>
     */
    public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses 
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }

    /**
     * Try to get Postal Code
     * @return null or postalCode
     */
    public String getPostalCode(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String postalCode = address.getPostalCode();

            return postalCode;
        } else {
            return null;
        }
    }

    /**
     * Try to get CountryName
     * @return null or postalCode
     */
    public String getCountryName(Context context) {
        List<Address> addresses = getGeocoderAddress(context);
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String countryName = address.getCountryName();

            return countryName;
        } else {
            return null;
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

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

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

注意

如果方法/答案不起作用。您需要使用官方的 Google Provider: FusedLocationProviderApi

文章:Getting the Last Known Location

【讨论】:

  • 感谢您的回答。但问题是,即使我启用了定位服务,我也会收到“启用 GPS 对话框”。我们如何解决这个问题?
  • 你的 Manifest 有这些配置: 你能用其他设备试试吗?
  • 如果 (gpsTracker.canGetLocation()) 出现这种情况下 canGetLocation() 的错误
  • 获取 0 值和空值
  • 每次 lat:0.0,lon:0.0
【解决方案2】:

重要提示:

请注意,这个 2015 年的解决方案可能太旧且已弃用。


以上方法都不适合我,所以我制作了一个教程并为自己编写了它,因为我在尝试实现它时浪费了很多时间。希望这可以帮助某人:

如何使用 Google Play 服务 LOCATION API 获取当前纬度和经度

1) 将ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION 添加到您的AndroidManifest.xml 文件中:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.appname" >

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

        <application...

2) 转到app/build.gradlefile 并添加以下依赖项(确保使用最新的可用版本):

    dependencies {
        //IMPORTANT: make sure to use the newest version. 11.0.1 is old AF
        compile 'com.google.android.gms:play-services-location:11.0.1
    }

3) 在您的活动中执行以下操作:

    import com.google.android.gms.common.ConnectionResult;
    import com.google.android.gms.common.api.GoogleApiClient;
    import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
    import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationServices;
    import com.google.android.gms.maps.GoogleMap;

    public class HomeActivity extends AppCompatActivity implements
            ConnectionCallbacks,
            OnConnectionFailedListener,
            LocationListener {

        //Define a request code to send to Google Play services
        private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
        private GoogleApiClient mGoogleApiClient;
        private LocationRequest mLocationRequest;
        private double currentLatitude;
        private double currentLongitude;


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

            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    // The next two lines tell the new client that “this” current class will handle connection stuff
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    //fourth line adds the LocationServices API endpoint from GooglePlayServices
                    .addApi(LocationServices.API)
                    .build();

            // Create the LocationRequest object
            mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                    .setFastestInterval(1 * 1000); // 1 second, in milliseconds

        }

        @Override
        protected void onResume() {
            super.onResume();
            //Now lets connect to the API
            mGoogleApiClient.connect();
        }

        @Override
        protected void onPause() {
            super.onPause();
            Log.v(this.getClass().getSimpleName(), "onPause()");

            //Disconnect from API onPause()
            if (mGoogleApiClient.isConnected()) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
                mGoogleApiClient.disconnect();
            }


        }

        /**
         * If connected get lat and long
         * 
         */
        @Override
        public void onConnected(Bundle bundle) {
            Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

            if (location == null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

            } else {
                //If everything went fine lets get latitude and longitude
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();

                Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
            }
        }


        @Override
        public void onConnectionSuspended(int i) {}

        @Override
        public void onConnectionFailed(ConnectionResult connectionResult) {
            /*
             * Google Play services can resolve some errors it detects.
             * If the error has a resolution, try sending an Intent to
             * start a Google Play services activity that can resolve
             * error.
             */
            if (connectionResult.hasResolution()) {
                try {
                    // Start an Activity that tries to resolve the error
                    connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    /*
                     * Thrown if Google Play services canceled the original
                     * PendingIntent
                     */
                } catch (IntentSender.SendIntentException e) {
                    // Log the error
                    e.printStackTrace();
                }
            } else {
                /*
                 * If no resolution is available, display a dialog to the
                 * user with the error.
                 */
                Log.e("Error", "Location services connection failed with code " + connectionResult.getErrorCode());
            }
        }

        /**
         * If locationChanges change lat and long
         * 
         * 
         * @param location
         */
        @Override
        public void onLocationChanged(Location location) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();

            Toast.makeText(this, currentLatitude + " WORKS " + currentLongitude + "", Toast.LENGTH_LONG).show();
        }

    }

如果您需要更多信息,请访问:

The Beginner’s Guide to Location in Android

注意:这在模拟器中似乎不起作用,但在设备上却可以正常工作

【讨论】:

  • 现在是 8.4.0:compile: com.google.android.gms:play-services-location:8.4.0
  • 这很棒。非常简单的答案,就像一个魅力。有多少例子试图简单地显示我必须经过的位置才能吐出纬度和经度。伟大而简单的答案,再次感谢!
  • @VincentRusso,我的荣幸 :)
  • 非常感谢您,这非常有效,并且提供了经纬度。
  • 我收到一个错误,我的应用程序崩溃了。它说:java.lang.SecurityException: Client must have ACCESS_FINE_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
【解决方案3】:

使用位置监听方法

@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}

【讨论】:

    【解决方案4】:

    您可以使用以下类作为服务类在后台运行您的应用程序

    import java.util.Timer;
    import java.util.TimerTask;
    
    import android.app.Service;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Handler;
    import android.os.IBinder;
    import android.widget.Toast;
    
    public class MyService extends Service {
    
        private GPSTracker gpsTracker;
        private Handler handler= new Handler();
        private Timer timer = new Timer();
        private Distance pastDistance = new Distance();
         private Distance currentDistance = new Distance();
        public static double DISTANCE;
        boolean flag = true ;
        private double totalDistance ;
        @Override
        @Deprecated
        public void onStart(Intent intent, int startId) {
    
            super.onStart(intent, startId);
            gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
            TimerTask timerTask = new TimerTask() {
    
                @Override
                public void run() {
                    handler.post(new Runnable() {
    
                        @Override
                        public void run() {
                            if(flag){
                                pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                                pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                                flag = false;
                            }else{
                                currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                                currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                                flag = comapre_LatitudeLongitude();
                            }
                            Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();
    
                        }
                    });
    
    
                }
            };
    
            timer.schedule(timerTask,0, 5000);
    
        }
    
        private double distance(double lat1, double lon1, double lat2, double lon2) {
              double theta = lon1 - lon2;
              double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
              dist = Math.acos(dist);
              dist = rad2deg(dist);
              dist = dist * 60 * 1.1515;
               return (dist);
            }
    
           private double deg2rad(double deg) {
              return (deg * Math.PI / 180.0);
            }
           private double rad2deg(double rad) {
              return (rad * 180.0 / Math.PI);
       }
    
    
        @Override
        public IBinder onBind(Intent intent) {
    
            return null;
        }
    
    
    
        @Override
        public void onDestroy() {
    
            super.onDestroy();
            System.out.println("--------------------------------onDestroy -stop service ");
            timer.cancel();
            DISTANCE = totalDistance ;
        }
        public boolean comapre_LatitudeLongitude(){
    
            if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
                return false;
            }else{
    
                final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
                System.out.println("Distance in mile :"+distance);
                handler.post(new Runnable() {
    
                    @Override
                    public void run() {
                        float kilometer=1.609344f;
    
                        totalDistance = totalDistance +  distance * kilometer;
                        DISTANCE = totalDistance;
                        //Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();
    
                    }
                });
    
                return true;
            }
    
        }
    
    }
    

    添加另一个类以获取位置

    import android.app.Service;
    import android.content.Context;
    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.util.Log;
    
    public class GPSTracker implements LocationListener {
    private final Context mContext;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    Location location = null; 
    double latitude; 
    double longitude; 
    
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
    
    protected LocationManager locationManager;
    private Location m_Location;
     public GPSTracker(Context context) {
        this.mContext = context;
        m_Location = getLocation();
        System.out.println("location Latitude:"+m_Location.getLatitude());
        System.out.println("location Longitude:"+m_Location.getLongitude());
        System.out.println("getLocation():"+getLocation());
        }
    
    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);
    
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
    
            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 Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS", "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;
    }
    
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker.this);
        }
    }
    
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
    
        return latitude;
    }
    
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
    
        return longitude;
    }
    
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
    
    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
    
    }
    
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
    
    }
    
    
    }
    

    // --------------Distance.java

     public class Distance  {
        private double latitude ;
        private double longitude;
            public double getLatitude() {
                return latitude;
            }
            public void setLatitude(double latitude) {
                this.latitude = latitude;
            }
            public double getLongitude() {
                return longitude;
            }
            public void setLongitude(double longitude) {
                this.longitude = longitude;
            }
    
    
    
    }
    

    【讨论】:

    • 你能有这段代码的示例演示应用程序吗?这真的很有帮助
    【解决方案5】:

    **活动应该实现LocationListener

    在onCreate()中,编写如下代码**

      Boolean network = haveNetworkConnection();
        Log.e("network", "---------->" + network);
        if (!network) {
            Toast.makeText(getApplicationContext(), "Network is not available",
                    3000).show();
    
        }
    
        SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.googleMap);
        googleMap = supportMapFragment.getMap();
        googleMap.setMyLocationEnabled(true);
    
    
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
    
    
    
    
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                && !locationManager
                        .isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    
    
    
             TextView title = new TextView(context);
             title.setText("Location Services Not Active");
                title.setBackgroundColor(Color.BLACK);
                title.setPadding(10, 15, 15, 10);
                title.setGravity(Gravity.CENTER);
                title.setTextColor(Color.WHITE);
                title.setTextSize(22);
    
    
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
    
    
    
    
            builder.setCustomTitle(title);
    
    
            // builder.setTitle("Location Services Not Active");
            builder.setMessage("Please enable Location Services and GPS");
    
            builder.setPositiveButton("Turn on",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialogInterface,
                                int i) {
                            // Show location settings when the user acknowledges
                            // the alert dialog
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    
                            startActivity(intent);
                            finish();
                        }
                    });
    
            builder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
    
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            dialog.cancel();
                        }
                    });
    
            builder.show();
    
        }
    
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(bestProvider);
    
        if (location == null) {
            Toast.makeText(getApplicationContext(), "GPS signal not found",
                    3000).show();
        }
        if (location != null) {
            Log.e("locatin", "location--" + location);
    
            Log.e("latitude at beginning",
                    "@@@@@@@@@@@@@@@" + location.getLatitude());
            onLocationChanged(location);
        }
    

    写一个方法haveNetworkConnection

    private boolean haveNetworkConnection() {
        boolean haveConnectedWifi = false;
        boolean haveConnectedMobile = false;
    
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    haveConnectedWifi = true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    haveConnectedMobile = true;
        }
        return haveConnectedWifi || haveConnectedMobile;
    }
    
    
    
    @Override
    public void onLocationChanged(Location location) {
    
    
        LatLng latLng = new LatLng(latitude, longitude);
        googleMap.addMarker(new MarkerOptions()
                .position(latLng)
                .title("Current LOC")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_RED)));
    
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
    
    
    }
    
    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
    }
    
    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
    }
    

    【讨论】:

      【解决方案6】:

      这是您可以使用的 Android 位置库 无需使用 Google 帐户或订阅即可找到您当前的位置。

      找到此链接并下载存储库

      https://github.com/mrmans0n/smart-location-lib

      保重,享受……

      【讨论】:

        【解决方案7】:

        试试这个,希望它能帮助你在每次位置变化时获取当前位置。

        public class MyClass implements LocationListener {
            double currentLatitude, currentLongitude;
        
            public void onLocationChanged(Location location) {
                currentLatitude = location.getLatitude();
                currentLongitude = location.getLongitude();
            }
        }
        

        【讨论】:

        • @deHaar 我不知道怎么称呼它。如果我使用`new MyClass()`,它会调用它。还是我需要别的东西。请告诉我
        • @shiv 对不起,我不能告诉你,因为这不是我的答案,我只是编辑了代码以使其以简洁的方式显示......问 fazeel zama,他发布了这个答案。
        【解决方案8】:

        对于这种多孔,您可以使用流动代码:

        public class GetLocationActivity extends BaseActivity {
        //for getting update of location
        FusedLocationProviderClient fusedLocationClient;
        //new callback result requesting in activity
        ActivityResultLauncher<String[]> locationPermissionRequest =
                registerForActivityResult(new ActivityResultContracts
                                .RequestMultiplePermissions(), result -> {
                            Boolean fineLocationGranted = result.get(
                                    Manifest.permission.ACCESS_FINE_LOCATION);
                            Boolean coarseLocationGranted = result.get(
                                    Manifest.permission.ACCESS_COARSE_LOCATION);
                            if (fineLocationGranted != null && fineLocationGranted) {
                                // Precise location access granted.
                                if (coarseLocationGranted != null && coarseLocationGranted) {
                                    // Only approximate location access granted.
                                    //chek is Gps is On or Off and ask from user to enable is
                                    checkGPS();
                                }
                            } else {
                                // No location access granted.
                                //show toast for errors
                            }
                        }
                );
        
        private void checkGPS() {
        //create call for checking gps sensor
            LocationRequest locationRequest = LocationRequest.create();
        
            LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        
            SettingsClient settingsClient = LocationServices.getSettingsClient(this);
            Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());
        
            task.addOnSuccessListener(this, locationSettingsResponse -> {
                Log.d("GPS_main", "OnSuccess");
                // GPS is ON
            });
        
            task.addOnFailureListener(this, new OnFailureListener() {
                @Override
                public void onFailure(@NonNull final Exception e) {
                    Log.d("GPS_main", "GPS off");
                  
                    // GPS off
                    if (e instanceof ResolvableApiException) {
                        ResolvableApiException resolvable = (ResolvableApiException) e;
                        try {
                            resolvable.startResolutionForResult(GetLocationActivity.this, 1);
                        } catch (IntentSender.SendIntentException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            });
        }
        
        
        
        
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
           
            fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
        
            //location button
            findViewById(R.id.lastLocationFab).setOnClickListener(view -> getPermission());
           
        }
        
        private void getPermission() {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //call request
                locationPermissionRequest.launch(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
        
            } else {
                fusedLocationClient.requestLocationUpdates(LocationRequest.create()
                                .setInterval(36000).setFastestInterval(36000)
                                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                                .setMaxWaitTime(1000),
                        getLocationCallback(), Looper.myLooper());
                getCurrentLocation();
            }
        }
        
        private LocationCallback getLocationCallback() {
            return new LocationCallback() {
                @Override
                public void onLocationResult(LocationResult locationResult) {
                    List<Location> locationList = locationResult.getLocations();
                    if (locationList.size() > 0) {
                        //The last location in the list is the newest
                        Location location = locationList.get(locationList.size() - 1);
        
                    
                        //Place current location marker
                      
                    }
                }
        
                
            };
        }
        
        
        public void getCurrentLocation() {
            fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() {
                @Override
                public boolean isCancellationRequested() {
                    return false;
                }
        
                @NonNull
                @Override
                public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) {
                    return null;
                }
            }).addOnSuccessListener(this, location -> {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    LatLng myLoc = new LatLng(location.getLatitude(), location.getLongitude());
                   
                }
            });
        
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-08-31
          • 2017-05-09
          • 2012-07-08
          • 2011-09-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多