0

我创建了一项服务,将设备的位置发送到服务器,然后该位置存储在数据库中。

在该服务中,我实现了一个 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();



            }
4

1 回答 1

1

stopSelf()是一个请求,它取决于运行时处理请求的时间。这是一种异步方法调用,因此人们可能不会期望在调用此方法时服务会立即结束。此外,在您的情况下,您的服务停止时似乎会触发更多位置更新,因此您可以使用locationManager.removeUpdates(locationListener);将其放在之前停止侦听位置更新stopSelf();

于 2012-04-07T13:18:18.850 回答