我一直在测试 LocationListener ( http://developer.android.com/reference/android/location/LocationListener.html ),并实现了抽象 onLocationChange。
在 onLocationChange 方法中,我修改了主 Activity 中的 TextView 以显示实际的坐标变化。
一旦 Activity 开始并且 GPS 开始连接后,TextView 就会根据每次坐标变化进行正确更新。
- 我仍然想知道这是怎么可能的,因为我还没有实现 针对 TextView 的 AsyncTask 或辅助线程?
- 如果该过程不是异步的,TextViews 如何每次更新 时间?
- 我难道不应该只看到 TextView 的一次更新,或更糟糕的是根本看不到吗?
这是我的代码:
package com.example.androidgps_get_coordinates;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView_lat;
TextView textView_long;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_lat=(TextView)findViewById(R.id.textV_lat);
textView_long=(TextView)findViewById(R.id.textV_long);
String serviceString=Context.LOCATION_SERVICE;
LocationManager locationManager; //remember to import LocationManager
locationManager=(LocationManager)getSystemService(serviceString);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
new LocationListener() {
public void onLocationChanged(Location location) {
textView_lat.setText(String.valueOf(location.getLatitude()));
textView_long.setText(String.valueOf(location.getLongitude()));
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
}
);
String provider=LocationManager.GPS_PROVIDER;
Location l= locationManager.getLastKnownLocation(provider);
}
最佳答案
onLocationChange
每次获取位置时都会被调用,因此 TextView
将会更新,因为您在 UI 线程中运行它。是什么让您认为您需要 AsyncTask
或单独的 Thread
?
另一件事是,在尝试读取 Location
之前检查它的 null
值是一个好习惯。
关于java - Android:GPS Geocoding onLocationChanged方法,为什么View元素会异步更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19488967/