2010.12.27——— android service
参考:[url]http://apps.hi.baidu.com/share/detail/23409277[/url]
需求:在应用开启时,启动一个service 不断的获得当前的gps数据
代码:
service:
清单文件:
调用:
总结:
[list]
[*]startService:应用退出了 仍然运行 比如说mp3的播放
[*]
[*]bindService 应用退出 也就结束了
[/list]
参考:[url]http://apps.hi.baidu.com/share/detail/23409277[/url]
需求:在应用开启时,启动一个service 不断的获得当前的gps数据
代码:
service:
package com.huitu.project;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import com.huitu.util.HttpUtil;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
public class GPSService extends Service{
private String user_id;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
LocationManager locationManager; locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
user_id = intent.getStringExtra("user_id");
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateMap(location,user_id);
LocationListener ll = new LocationListener(){
public void onLocationChanged(Location location) {
updateMap(location,user_id);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
locationManager.requestLocationUpdates(provider, 500, 5,
ll);
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
private void updateMap(Location location,String user_id){
System.out.println("gps run");
double lat=0.0;
double lng = 0.0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
String url = HttpUtil.BASE_URL+"android_addGPS_M.action?lat="+lat+"&lng="+lng+"&user_id="+user_id;
try {
HttpUtil.getHttpResponse(HttpUtil.getHttpPost(url));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
清单文件:
<service android:name=".GPSService"></service>
调用:
Intent service = new Intent(this,GPSService.class);
service.putExtra("user_id", result[1]);
intent.putExtra("user_id", result[1]);
intent.putExtra("org_id", result[2]);
//startService(service);
bindService(service, null, BIND_AUTO_CREATE);
总结:
[list]
[*]startService:应用退出了 仍然运行 比如说mp3的播放
[*]
[*]bindService 应用退出 也就结束了
[/list]