我创建了一项服务,将设备的位置发送到服务器,然后该位置存储在数据库中。
在该服务中,我实现了一个 LocationListner 并在 onLocationChanged 方法中通过 HttpPost 将位置发送到服务器,为服务设置警报(因为我希望它每小时发送一次位置)然后停止服务。
问题是即使我调用了“stopself”,服务也会在停止之前继续运行几次(如多次发送位置)。我怎样才能改变它,以便他的服务立即停止。
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();
}