我创建了一项服务,将设备的位置发送到服务器,然后将该位置存储在数据库中。
在该服务中,我实现了一个LocationListner,并在onLocationChanged方法中,通过HttpPost将服务器发送到服务器的位置设置服务的警报(因为我希望它每小时发送一次),然后停止服务
问题是即使我称之为'自己',服务在停止前继续运行几次(如发送位置几次)。如何更改它以便他立即停止服务。
PFB onLocationChanged方法的代码
public void onLocationChanged(android.location.Location location) {
if(location!=null)
{
System.out.println("here");
latid = location.getLatitude();
longid = location.getLongitude();
String userinfo = ``Double.toString(latid)+"&&&&"+Double.toString(longid);
Location = userinfo;
Toast.makeText(getApplicationContext(), Location, 1000).show();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.easymontra.in/location/try.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", Double.toString(latid)));
nameValuePairs.add(new BasicNameValuePair("long", Double.toString(longid)));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Execute HTTP Post Request
try {
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 60);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
Toast.makeText(getApplicationContext(), "stopping now", 1000).show();
stopSelf();
}
答案 0 :(得分:1)
stopSelf()
是一个请求,它取决于运行时,它处理请求的时间。它是一个异步方法调用,因此当调用此方法时,可能不会期望服务立即结束。此外,在您的情况下,您的服务停止时会触发更多位置更新,因此您可以使用locationManager.removeUpdates(locationListener);
将其置于stopSelf();