我的Andoid应用程序包含许多活动。我想运行一个独立于这些活动的后台进程(无论哪个活动在UI上运行)。在这个后台进程中,我希望使用LocationListener捕获位置更新,并希望调用web服务将捕获的位置存储在数据库中。并且此webservice调用必须仅在2分钟间隔内发生。有没有人可以帮我实现这个。
谢谢。Android开发者
发布于 2012-04-13 14:51:31
看看这个
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());
}
}
}
}
}发布于 2012-04-13 14:39:24
也许值得在后台启动一个简单的AsyncTask来做这件事。
https://stackoverflow.com/questions/10136080
复制相似问题