我的 Andoid 应用程序包含许多活动。我想运行一个独立于这些活动的后台进程(无论 UI 上运行的是哪个活动)。在此后台进程中,我想使用 LocationListener 捕获位置更新,并希望调用 Web 服务将捕获的位置存储在数据库中。并且这种 web 服务的调用必须仅在 2 分钟间隔内发生。有人可以帮我实现这一点。
谢谢。安卓开发者
我的 Andoid 应用程序包含许多活动。我想运行一个独立于这些活动的后台进程(无论 UI 上运行的是哪个活动)。在此后台进程中,我想使用 LocationListener 捕获位置更新,并希望调用 Web 服务将捕获的位置存储在数据库中。并且这种 web 服务的调用必须仅在 2 分钟间隔内发生。有人可以帮我实现这一点。
谢谢。安卓开发者
Check this
public class LocationUpdator extends Service{
Location location;
private int normallocationwait = 2000;
Timer timer = new Timer();
private final Handler handler = new Handler();
Intent intent;
public void onCreate(){
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
updateNotification();
}
//int onStartCommand(Intent intent, int flags, int startId)
public void onStart(Intent intent,int startId){
super.onStart(intent, startId);
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
Log.v("Location Servics", "Start Service");
}
public void onDestroy(){
super.onDestroy();
Log.v("Location Servics", "Destroy Service");
}
protected void updateNotification() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, normallocationwait, 0.250f, locationListener);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
private class MyLocationlistener implements LocationListener {
public void onLocationChanged(Location location){
if(location!=null){
dumpLocation(location);
}
}
public void onProviderDisabled(String provider){
Log.v("Loc Update","\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider){
Log.v("Loc Update","\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras){
Log.v("Loc Update","\nProvider status changed: " + provider + ", status="
+ status + ", extras=" + extras);
}
private void dumpLocation(Location location) {
Log.v("Loc Update","\n" + location.toString());
Log.v("Demo", location.toString());
if(GlobalValues.whereRegister == 1){
String url = TaxiUrls.taxiLocationUpdate_url + "taxi_device_id="+ GlobalValues.deviceID +
"&lat="+ location.getLatitude() + "&lng=" + location.getLongitude();
Toast.makeText(getBaseContext(), "Location Update", Toast.LENGTH_SHORT).show();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
HttpResponse response = httpclient.execute(httppost);
Log.v("Message", response.toString());
} catch (ClientProtocolException e) {
Log.e("Sending Message",e.getMessage().toString());
} catch (IOException e) {
Log.e("Sending Message",e.getMessage().toString());
}
}
}
}
}
也许值得在后台启动一个简单的 AsyncTask 来执行此操作。