首页 > 解决方案 > 无法在应用程序中获取我手机的位置

问题描述

我正在 Android Studio 中构建将访问用户位置的应用程序。下面提供的是我正在使用的代码。我将手机本身用作模拟器。我已在清单 XML 文件中授予 ACCESS_FINE_LOCATION 和 ACCESS_INTERNET。

public class MainActivity extends AppCompatActivity {

    LocationManager locMan;
    LocationListener locList;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION ) == PackageManager.PERMISSION_GRANTED)
            {
                locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locList);
            }
        }
    }

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

        locMan = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locList = new LocationListener()
        {
            @Override
            public void onLocationChanged(Location location)
            {
                Toast.makeText(getApplicationContext(), location.toString(), Toast.LENGTH_SHORT).show();
// Here I am trying to make toast of my location. In place of 'getApplicationContext()' , I had passed 'MainActivity' but it also don't work.
            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle)
            {

            }

            @Override
            public void onProviderEnabled(String s)
            {

            }

            @Override
            public void onProviderDisabled(String s)
            {

            }
        };
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
        else
        {
            locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locList);
        }
    }
}

可以做什么?我的 GPS 有问题吗?

标签: javaandroidandroid-studiogoogle-maps

解决方案


根据您使用的 android 版本,您可能还需要使用 ACCESS_COARSE_LOCATION。尝试将其添加到您的清单并在您​​的活动中请求许可。

我曾经写过一个工人班来不断跟踪设备的位置。

private static LocationManager locationManager=null;
private static LocationListener locationListener=null;

public static void startTrackingLocation(final Context context, final LocationChangedListener listener) {
    startTrackingLocation(context, listener, 0.5, 1);
}
/**
 * Location gets requested periodically, and a call on abstract listener.onLocationChanged(Location l)
 * is performed if distance between locations is > distance
 * @param context   context to gather the location from
 * @param listener  listens to location changes
 * @param minutes   interval between the location requests
 * @param distance  minimal distance to trigger onLocationChanged(Location l)
 */
public static void startTrackingLocation(@NotNull final Context context, @NotNull final LocationChangedListener listener, final double minutes, final int distance) {
    initLocationManager(context);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            listener.onLocationChanged(location);
        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) { }
        @Override
        public void onProviderEnabled(String provider) { }
        @Override
        public void onProviderDisabled(String provider) { }
    };

    try {
        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, (int)(minutes*60000), distance, locationListener);
    } catch (SecurityException ignored) { }
}

private static void initLocationManager(@NotNull final Context context) {
    if (null==locationManager) {
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }
}

@SuppressWarnings("unused")
public static void stopTrackingLocation() {
    if (null!=locationManager && null!=locationListener) {
        locationManager.removeUpdates(locationListener);
    }
}

public static Location getLocation(final Context context) {
    initLocationManager(context);
    Location locationGPS=null, locationNet=null;
    try {
        locationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        locationNet = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    } catch (SecurityException ignored) { }

    if (null != locationNet) {
        return locationNet;
    }
    return locationGPS;
}
@SuppressWarnings("unused")
private static double distance(final double lat1, final double lon1, final double lat2, final double lon2) {
    final double theta = lon1 - lon2;
    double dist = Math.sin(Math.toRadians(lat1)) * Math.sin(Math.toRadians(lat2))
            + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.cos(Math.toRadians(theta));
    dist = Math.toDegrees(Math.acos(dist)) * 60 * 1850 ; // 1 degree is 111km 111/60=1.85
    return (dist);
}

LocationChangedListener 类是我编写的一个抽象类,用于捕获位置更改的事件。

代码非常简单:

 public abstract void onLocationChanged(Location location);

在您的活动中:

LocationChangedListener listener = new LocationChangedListener() {
        @Override
        public void onLocationChanged(Location location) {
            MainActivity.this.onLocationChanged(location);
        }
    };

这完全可以在我的安卓设备上运行,你可以试一试。此外,函数 Location getLocation(final Context context) 可能会被省略,因为它仅在给定时间为您提供设备位置。

我在清单中使用了相同的权限。这也应该对你有用。


推荐阅读