我有一个使用GPS-Tracker的离线地图应用程序。我的主要目标是感知纬度和经度的变化并更新TextView
。
我的GPS-Tracker
课程实施如下:
public class GPSTracker extends Service implements LocationListener {
...
public GPSTracker(Context context) {
...
getLocation();
}
public Location getLocation() {
// returns Location
}
@Override
public void onLocationChanged(Location location) {
// Method 1: update UI elements (textview) directly
MainActivity.tvGPS.setText("lat: " + Double.toString(location.getLatitude()) + "lon: " + Double.toString(location.getLongitude());
// Method 2: call a method from MainActivity which updates UI
MainActivity.setNewPosition(location.getLatitude() , location.getLatitude());
// Method 3: sense changes in Latitude and Longitude directly in MainActivity and update UI
}
}
问题:
如何直接感知纬度和经度的变化(在MainActivity
中)并修改UI。
我到目前为止测试的内容:
LocalBroacastManager
here但要求不断检查位置以检测更改
Observer Pattern
:仅Observer
类中的更改只适用于MainActivity
答案 0 :(得分:0)
您可以将MainActivity
作为参数传递给GPSTracker
的构造函数。
private TextView tvGPS;
public GPSTracker(Activity a) {
...
tvGPS = (TextView)a.findViewById(R.id.tvGPS); // whatever ID
}
然后您可以直接在onLocationChanged
。
@Override
public void onLocationChanged(Location location) {
tvGPS.setText("lat: " + Double.toString(location.getLatitude()) + "lon: " + Double.toString(location.getLongitude());
}
答案 1 :(得分:0)
请不要使用静态方法将Activity实例传递给跟踪器!这是非常糟糕的做法!
您可以使用活动总线。 http://square.github.io/otto/
创建一个总线提供商:
public class BusProvider {
private static final Bus BUS = new Bus(ThreadEnforcer.ANY);
public static Bus getInstance() {
return BUS;
}
private BusProvider() {
// No instances.
}
}
创建一个公交活动:
public class LocationChangedEvent{
private Location location;
private Location location;
public LocationChangedEvent(Location location) {
this.location = location;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
public class GPSTracker extends Service implements LocationListener {
...
public GPSTracker(Context context) {
...
getLocation();
}
public Location getLocation() {
// returns Location
}
@Override
public void onLocationChanged(Location location) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
BusProvider.getInstance().post(new LocationChangedEvent(location));
}
});
}
}
在您的活动中:
@Subscribe
public void onLocationUpdated(LocationChangedEvent locationChangedEvent){
//TODO update ui as you need
}
不要忘记注册/取消注册总线