YourService
LocationOperator
当位置改变时通知每个注册的人。LocationOperator
是一个简单的接口,声明operate(Location)
方法。
class YourService extends Service implements LocationListener {
private List<LocationOperator> listeners = new ArrayList<LocationOperator>();
public List<LocationOperator> getListeners() {
return listeners;
}
@Override
public void onLocationChanged(Location location) {
for (LocationOperator listener : listeners) {
listener.operate(location);
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// request location updates from `LOCATION_SERVICE`
return Service.START_NOT_STICKY;
}
//...
}
从您的主要活动启动并连接到此服务
public class MainActivity extends Activity {
static YourService yourService;
@Override
protected void onCreate(Bundle savedInstanceState) {
//...
Intent service = new Intent(this, YourService.class);
startService(service);
bindService();
}
// ...
}
然后您就可以访问此服务MainActivity
并注册Location
public class OperatorActivity extends Activity implements LocationOperator {
@Override
public void onCreate(Bundle instance) {
// ...
MainActivity.yourService.getListeners().add(this);
// ...
}
public void operate(Location location) {
// use location
}
}