Java 使用位置管理器和位置侦听器显示坐标
这是我们班的代码。文本视图在活动中,我的目标只是在文本视图中显示纬度和经度。现在,当我运行应用程序时,看起来什么都没有发生。文本视图只显示“文本视图” } 以下是XML:Java 使用位置管理器和位置侦听器显示坐标,java,android,Java,Android,这是我们班的代码。文本视图在活动中,我的目标只是在文本视图中显示纬度和经度。现在,当我运行应用程序时,看起来什么都没有发生。文本视图只显示“文本视图” } 以下是XML: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" andro
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/latitude_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="@+id/local_mbta_list"
android:layout_marginStart="40dp"
android:layout_marginTop="91dp"
android:text="TextView" />
<TextView
android:id="@+id/longitude_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/latitude_label"
android:layout_alignParentEnd="true"
android:layout_marginEnd="107dp"
android:text="TextView" />
</RelativeLayout>
GPS系统速度非常慢,您可以通过网络获取坐标。 这是官方的Android开发者指南 事实上,要以最快的方式检索坐标,可以使用以下方法:
Location loc;
try {
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}catch (Exception e){
//SecurityException if permissions are not enabled
loc = null;
e.printStackTrace();
}
if(loc!=null){//We can use coordinates, yay!
longitude = (float) loc.getLongitude();
latitude = (float) loc.getLatitude();
txtLatLng.setText(getString(R.string.latitude).concat(Float.toString(latitude)).concat(" ").concat(getString(R.string.longitude).concat(Float.toString(longitude))));
}else{//No last location updated so we must use slow GPS method
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}
在调用RequestLocationUpdate之前,您应该检查权限。您还应该在onRequestPermissionResults中请求LocationUpdate(如果已授予)。
Location loc;
try {
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}catch (Exception e){
//SecurityException if permissions are not enabled
loc = null;
e.printStackTrace();
}
if(loc!=null){//We can use coordinates, yay!
longitude = (float) loc.getLongitude();
latitude = (float) loc.getLatitude();
txtLatLng.setText(getString(R.string.latitude).concat(Float.toString(latitude)).concat(" ").concat(getString(R.string.longitude).concat(Float.toString(longitude))));
}else{//No last location updated so we must use slow GPS method
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);}