使用通用代码无法获取GPS位置

3

我有获取位置的代码,我相信它必须是有效的,但实际上它却不起作用:

清单文件:

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

Java:

    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            0, 
            0,
            new MyLocationListener()
    );

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);

    String provider = locationManager.getBestProvider(criteria, true);

    Location location = locationManager.getLastKnownLocation(provider);
    System.out.println("location: " + location);

位置信息返回为null,监听器根本没有被调用。有人能指导一下是哪里出了问题吗?如果我打开Google Maps,它总是能够返回我的位置。

注意:我正在使用我的设备进行测试。


请按照以下方式操作,只需检查此链接即可帮助您 https://dev59.com/UHI_5IYBdhLWcg3wJPZu - Jignesh Jain
mLocationManager是什么?因为在你的代码中你正在使用locationManager来注册更新,所以你应该使用locationManager。 - Gautam
@Gautam 抱歉忘记编辑那个。 - Rendy
2个回答

1
在你的实用程序包或任何你认为合适的地方,使用下面的代码创建类SingleShotLocationProvider
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

public class SingleShotLocationProvider {

    public  interface LocationCallback {
         void onNewLocationAvailable(Location location);
    }

    // calls back to calling thread, note this is for low grain: if you want higher precision, swap the
    // contents of the else and if. Also be sure to check gps permission/settings are allowed.
    // call usually takes <10ms
    public static void requestSingleUpdate(final Context context, final LocationCallback callback) {
        final LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);


        if (Utility.checkAndRequestPermissionsForGPS(context)) {
            if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(context, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
                return;
            }
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

            if (isGPSEnabled) {
                Criteria criteria = new Criteria();
                criteria.setAccuracy(Criteria.ACCURACY_FINE);
                locationManager.requestSingleUpdate(criteria, new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        callback.onNewLocationAvailable(location);
                    }

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

                    @Override
                    public void onProviderEnabled(String provider) {
                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                    }
                }, null);
            } else {
                boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (isNetworkEnabled) {
                    Criteria criteria = new Criteria();
                    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
                    locationManager.requestSingleUpdate(criteria, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            callback.onNewLocationAvailable(location);
                        }

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

                        @Override
                        public void onProviderEnabled(String provider) {
                        }

                        @Override
                        public void onProviderDisabled(String provider) {
                        }
                    }, null);
                }
            }
        }

    }

}

现在在你的 Activity 中像这样导入它:
import com.yourdomain.utils.SingleShotLocationProvider;

现在您可以像下面这样使用它:this 是指向您的活动的引用。
 SingleShotLocationProvider.requestSingleUpdate(this,
                    new SingleShotLocationProvider.LocationCallback() {
                        @Override
                        public void onNewLocationAvailable(Location location) {
                            if (location != null) {
                                double latitude = location.getLatitude();
                                double longitude = location.getLongitude();
                                }
                             } 
                    }
                });

您将在第一次尝试中接收位置信息,只需确保GPS已开启并设置为高精度。在清单文件中,您已经给出了必要的权限,如下所示 -

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

0

尝试这段代码。我在这里使用GPS获取纬度和经度。

   Criteria criteria = new Criteria();

    // Getting the name of the best provider
    provider = locationManager.getBestProvider(criteria, true);

    // Getting Current Location
    location = locationManager.getLastKnownLocation(provider);

    if (location != null) {
        System.out.println("Get Last LOcation" + location.getLatitude()
                + location.getLongitude());
        loc.setLatitude(location.getLatitude());
        loc.setLongitude(location.getLongitude());

    }
    locationListener = new LocationListener() {

        @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

        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub
            if (location.getAccuracy() < 50) {
                locationManager.removeUpdates(locationListener);
            }
        }
    };

    locationManager.requestLocationUpdates(provider,
            INTERVAL_TIME_SECONDS, MIN_DISTANCE_METERS,
            locationListener);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接