【问题标题】:I can not get the location from Location manager in android我无法从 android 的位置管理器中获取位置
【发布时间】:2014-12-02 12:05:48
【问题描述】:

在我的应用程序中,我将检查 GPS 是否启用。如果未启用,我会将页面重定向到 GPS 设置。

启用 GPS 后,我将从 LocationManager 获取位置。但是我找不到位置。

在这里我附上了我的代码。

if (isGPSEnabled())
{
getLocation();
}



private boolean isGPSEnabled() {
        boolean gpsEnabled = false;
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            gpsEnabled = true;
            return gpsEnabled;
        } else {
            showGPSDisabledAlertToUser();
        }
        return gpsEnabled;
    }



private void showGPSDisabledAlertToUser() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder
                .setMessage(
                        "GPS is disabled in your device. Would you like to enable it?")
                .setCancelable(false)
                .setPositiveButton("Goto Settings Page To Enable GPS",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Intent callGPSSettingIntent = new Intent(
                                        android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(callGPSSettingIntent);
                            }
                        });

        alertDialogBuilder.setNegativeButton("Cancel",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = alertDialogBuilder.create();
        alert.show();
    }



private void getLocation() {
        LocationManager  locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            onLocationChanged(location);
        } else {

        }
    }



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

请告诉我我犯了什么错误?

提前谢谢..

【问题讨论】:

  • 你是用真机还是安卓模拟器测试?如果您使用的是设备,它是哪一个?还要记住,GPS 在室内效果不佳,如果您在室外或靠近窗户的地方尝试可能会更好(我过去也遇到过类似的情况)。但是,LastKnownLocation 策略应该如您所说。
  • 愿此链接对您有所帮助stackoverflow.com/questions/4772686/…
  • 我犯了什么错误??我认为每件事都是正确的。当我尝试在不使用 GPS 启用方法的情况下运行我的应用程序时(我隐藏了该方法,并且我手动在 GPS 上),它正在工作。当我尝试添加 GPS 启用方法时,位置未显示..

标签: android gps


【解决方案1】:

我认为问题在于您从不向 LocationManager 请求新位置。

private void getLocation() {
    LocationManager  locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    if (location != null) {
        onLocationChanged(location);
    } else {
        locationManager.requestSingleUpdate(provider, myLocationListener, null);
    }
}

【讨论】:

    【解决方案2】:

    这是我的Ready made class for finding Location

    import android.app.AlertDialog;
    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.util.Log;
    public class FindGPSLocation 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 FindGPSLocation(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(FindGPSLocation.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 is settings");
    
                // Setting Dialog Message
                alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
    
                // On pressing Settings button
                alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int which) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        mContext.startActivity(intent);
                    }
                });
    
                // on pressing cancel button
                alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                    }
                });
    
                // Showing Alert Message
                alertDialog.show();
            }
    
            @Override
            public void onLocationChanged(Location location) {
            }
    
            @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;
            }
    
    }
    

    Now Use following code in your activity in which you want to get the latitude and longtide.

    FindGPSLocation gps;
    gps = new FindGPSLocation(CurrentLocation.this);
    if(gps.canGetLocation()){
    
                    latitude = gps.getLatitude();
                    longitude = gps.getLongitude();
                    //Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();    
                }else{
    
                    gps.showSettingsAlert();
                }
    

    这段代码对我有用。

    【讨论】:

    • 你也可以添加导入吗?因为我无法解决一些进口问题。
    • 已添加,请查看,让我知道
    • 不能在移动设备上运行。而且也没有显示启用 GPS 设置。
    • 您是否设置了 GPS 或位置设置?
    • 是的.. 我在我的位置。但不能在移动设备上运行。
    【解决方案3】:

    请不要使用旧的位置提供程序,它们已经过时了。您需要使用作为 Google Play 服务一部分的融合位置提供程序。我在这里有一个完整的工作示例:

    https://github.com/nickfox/GpsTracker/tree/master/phoneClients/android

    使用 Android Studio 构建。我还有一个教程解释了它是如何工作的:

    https://www.websmithing.com/2014/04/23/how-the-gpstracker-android-client-works/

    最后,要详细了解新的 Android 定位服务,请阅读以下内容:

    https://developer.android.com/google/play-services/location.html

    【讨论】:

    • 这是真的,但没有尝试回答问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2016-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多