我试图让我的服务每 5 秒将手机的坐标发送到我的服务器,但我不知道为什么它不起作用。
(尽管它确实适用于非服务活动。(当调用 OnClick 方法时 - 单击按钮。
这就是为什么它在服务中不起作用这一事实很奇怪。)这是我的代码:
public class LocationService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// I Dont Know what this method does.
Execute();
return null;
}
String lat="", lon="";
public void Execute()
{
new PostAsyncTask().execute();
}
public void ReNewCoordinates(){
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
lat = Double.toString(location.getLatitude());
lon = Double.toString(location.getLongitude());
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,Bundle extras) {}};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
ReNewCoordinates();
//new PostAsyncTask().execute();
}
public void postData(String la, String lo) {
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.myserver.com/insert.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("user","100nir100"));
nameValuePair.add(new BasicNameValuePair("lat", lat));
nameValuePair.add(new BasicNameValuePair("lon", lon));
nameValuePair.add(new BasicNameValuePair("address", GetAddress(lat, lon)));
UrlEncodedFormEntity form;
form = new UrlEncodedFormEntity(nameValuePair);
form.setContentEncoding(HTTP.UTF_8);
try {
httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(nameValuePair,"UTF-8"));
} catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}
try
{
HttpResponse response = httpClient.execute(httpPost);
int status=response.getStatusLine().getStatusCode();//200=success 300=redirection 400=client error 500 = server error
if(status==200)
{
HttpEntity e=response.getEntity();
String data=EntityUtils.toString(e);
Integer x= Integer.valueOf(data.trim());//very important to use trim
if(x==1)
{
Toast.makeText(this, "Sucssess", Toast.LENGTH_SHORT).show();
}
else if(x!=1)
{
Toast.makeText(this, "Unsucssessful", Toast.LENGTH_SHORT).show();
}
Toast.makeText(this, "Unsucssessful", Toast.LENGTH_SHORT).show();
}
}
catch (ClientProtocolException e) {
// writing exception to log
e.printStackTrace();
} catch (IOException e) {
// writing exception to log
e.printStackTrace();
}
}
catch (Exception e) {
// TODO: handle exception
}
}
public String GetAddress(String lat, String lon)
{
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
String ret = "";
try {
List<Address> addresses = geocoder.getFromLocation(Double.parseDouble(lat), Double.parseDouble(lon), 1);
if(addresses != null) {
Address returnedAddress = addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
}
ret = strReturnedAddress.toString();
}
else{
ret = "No Address returned!";
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ret = "Can't get Address!";
}
return ret;
}
class PostAsyncTask extends AsyncTask<String, Integer, Boolean> {
protected Boolean doInBackground(String... params) {
postData(lat, lon);
return true;
}
protected void onPreExecute() {
// show progress dialog
}
protected void onPostExecute(Long result) {
// hide progress dialog
}
}
public int onStartCommand(Intent intent, int flags, int startId) {
//new PostAsyncTask().execute();
new Thread(new Runnable(){
public void run() {
while(true){
new PostAsyncTask().execute();
try{
Thread.sleep(5000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return Service.START_STICKY;
}
public void OnStart()
{
Execute();
}
public void OnDestroy()
{
super.onDestroy();
//Thread.stop();
}
}
那么如何让服务每 5 秒执行一次呢?谢谢你的帮助!