繁体   English   中英

在android中获取当前位置(坐标)?

[英]Getting current location (coordinates) in android?

我正在尝试获取经度和纬度的当前位置坐标。 到目前为止,这是我的代码:

public class MainActivity extends AppCompatActivity {

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

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    MyLocationListener myLocationListener = new MyLocationListener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);

}

}

这节课也是:

public class MyLocationListener implements LocationListener {
private static final String TAG = "COORDINATES: ";

@Override
public void onLocationChanged(Location location) {
    if(location != null){
        Log.e(TAG, "Latitude: " + location.getLatitude());
        Log.e(TAG, "Longitude: " + location.getLongitude());
    }
}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}

}

当我在模拟器中运行应用程序时,我没有得到任何带有坐标的日志消息。 有什么建议么?

最好的方法是使用Google Play服务库提供的最新FusedLocationApi。

如果您想使用旧方法,那很好,但是您可能不会获得非常准确的结果。

无论哪种方式,请确保您已在Android清单中启用了Internet权限(COARSE_LOCATION或FINE_LOCATION或两者都启用)。

此外,如果您使用的是Android 6.0,请记住您必须请求运行时权限,否则将无法使用!

昨天我回答了类似的问题,您可以在这里找到-可行的方法;

还有为FusedLocationApi样本代码的链接在这里

希望这对您有帮助,祝您好运!

更新

您可以像这样将Google Play服务添加到build.gradle中:

compile 'com.google.android.gms:play-services:9.2.'

但是,如果您仅对诸如位置之类的一项服务感兴趣,则可以具体说明:

compile 'com.google.android.gms:play-services-location:9.2.1'

注意

我强烈不建议您在UI线程上获取用户位置,因为从长远来看,这将破坏用户体验! 使用单独的线程!

您必须模拟模拟器中的位置。 您可以通过访问Android设备管理器并选择“仿真器控制”选项卡并将位置发送到仿真器来实现。

模拟器中的位置设置

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM