我有一个名为message.java的活动,它绑定到服务GPS.java。从GPS.java获得的纬度和经度必须在message.java中使用。我们使用servicebinder获取onServiceConnected()中的纬度和经度的默认值。 这是message.java的代码
`Intent i=new Intent(getApplicationContext(), GPS.class);
bindService(i,mConnection,Context.BIND_AUTO_CREATE)
private GPS servicebinder;
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
servicebinder = ((GPS.MyBinder)service).getService();
double lat=servicebinder.getlatitude();
double lon=servicebinder.getlongitude();
tex.setText("\nlatitude: " + lat+ "\nlongitude: "
+ lon);
// do any extra setup that requires your Service
}
getLatitude()和getLongitude()返回GPS.java中找到的纬度和经度,这是正确的。问题是上面显示的lat和lon打印了默认值,所以当服务中的纬度和经度更新时,我希望lat和lon也应该更新(应该在服务更新时通知Activity)
请提供适当的代码
答案 0 :(得分:0)
首先按照以下
创建MyLocationListener
之类的界面
public interface MyLocationListener {
public void locationChanged(double lat, double lon);
}
现在将GPS
课程更新为
public class GPS {
ArrayList<MyLocationListener> listeners = new ArrayList<MyLocationListener>();
public void addLocationListener(MyLocationListener listener) {
listeners.add(listener);
}
}
所以,如果你改变纬度或经度,只需调用
notifyChangeLocation(lat, lon);
并且此方法具有以下代码:
public void notifyChangeLocation(double lat, double lon) {
Iterator<MyLocationListener> itr = listeners.iterator();
while(itr.hasNext()) {
itr.next().locationChanged(lat, lon);
}
}
这是第一部分,现在第二部分是通过创建一个类MyServiceConnection
来在您的活动中添加监听器,如下所示:
public class MyServiceConnection implements ServiceConnection, MyLocationListener {
//add the unimplemented methods
public void locationChanged(double lat, double lon) {
// do any extra setup that requires your Service
}
}
ServiceConnection mConnection = new MyServiceConnection();
Intent i=new Intent(getApplicationContext(), GPS.class);
bindService(i,mConnection,Context.BIND_AUTO_CREATE);
现在只需注册听众
gps.addLocationListener(mConnection);