在您的服务中定义一个侦听器,如下所示:
// listener ----------------------------------------------------
static ArrayList<OnNewLocationListener> arrOnNewLocationListener =
new ArrayList<OnNewLocationListener>();
// Allows the user to set a OnNewLocationListener outside of this class and
// react to the event.
// A sample is provided in ActDocument.java in method: startStopTryGetPoint
public static void setOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.add(listener);
}
public static void clearOnNewLocationListener(
OnNewLocationListener listener) {
arrOnNewLocationListener.remove(listener);
}
// This function is called after the new point received
private static void OnNewLocationReceived(float myValue) {
// Check if the Listener was set, otherwise we'll get an Exception when
// we try to call it
if (arrOnNewLocationListener != null) {
// Only trigger the event, when we have any listener
for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
arrOnNewLocationListener.get(i).onNewLocationReceived(
myValue);
}
}
}
}
并像这样在您的活动中注册它:
OnNewLocationListener onNewLocationListener = new OnNewLocationListener() {
@Override
public void onNewLocationReceived(float myValue) {
//use your value here
MyService.clearOnNewLocationListener(this);
}
};
// start listening for new location
MyService.setOnNewLocationListener(
onNewLocationListener);
有关更多信息,请查看此链接:https ://stackoverflow.com/a/7709140/779408