【发布时间】:2014-02-05 20:41:39
【问题描述】:
我的应用程序,要求是在后台启动我的服务,当某些甚至发生时,例如拨打特定的电话号码。在那次事件之后,我需要获取用户位置并将其发送到网络。
这是我到目前为止所做的,广播接收器来处理事件,然后我启动我的服务。 我正在使用该服务来获取用户当前位置,为此我在后台运行我的服务,对于这个循环器和消息概念,通过覆盖handleMessage,并通过onStartCommand 覆盖传递意图信息。 这是代码
@Override
public boolean handleMessage(Message message) {
Intent intent = (Intent) message.obj;
String action = intent.getAction();
if (START_EMERGENCY_SERVICE_ACTION.equalsIgnoreCase(action)) {
startMonitoring();
} else if (STOP_EMERGENCY_SERVICE_ACTION.equalsIgnoreCase(action)){
stopMonitoring();
stopSelf();
}
return true;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mHandler.sendMessage(mHandler.obtainMessage(0, intent));
return START_STICKY;
}
private void startMonitoring() {
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener, mHandlerThread.getLooper());
}
在我的位置侦听器类中,我在其位置更新方法上正确获取了当前位置。
@Override
public void onLocationChanged(Location location) {
Location bestLocation = getBestLocation(location);
if (bestLocation != lastLocation) {
Log.i(getClass().getSimpleName(),
String.format("Location Changed %s @ %d %f:%f (%f meters)",
bestLocation.getProvider(),
bestLocation.getTime(),
bestLocation.getLatitude(),
bestLocation.getLongitude(),
bestLocation.getAccuracy()));
}
}
现在,我的挑战是将此位置发送到我的网络服务器,该服务器有一个休息 API。以前我在一个活动中使用了带有 AsyncTask 的 httpUtil,但是如何在后台活动中做同样的事情。我应该启动另一个后台服务来进行服务器通信吗?我也对其他架构更改持开放态度。
我必须从 2.3 开始支持,现在我使用的是旧的定位方式,但将来它应该具有足够的可扩展性,可以迁移到融合定位。
【问题讨论】:
标签: java android service android-service