我有一个LocationService
类(扩展Service
实现LocationListener
),只要通过onLocationChanged
方法获得新位置,它就会不断更新全局变量。
在我的启动器活动的onCreate
方法中,我启动此服务。我接下来要做的是调用一个从全局变量中获取纬度和经度的Web服务。
这给了我一个位置全局变量的NullPointerException
,我假设它,因为服务在一个单独的线程上运行,还没有获得一个位置。
问题:如何才能使我只在从服务类获得位置时才调用Web服务?
非常感谢。 :)
答案 0 :(得分:0)
我认为等待时间并不好(取决于浪费的时间),因为活动永远无法启动,但您可以尝试使用这个简单的代码:
While(latitude == null);
use latitude and longitude
continue with oncreate...
但我的建议是尝试与其他AsyncTask一起检查,以便不进行主动等待。希望它可以帮到你。
答案 1 :(得分:0)
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
}
}