Java 如何在应用程序关闭时禁用 Android LocationListener

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9764169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:23:20  来源:igfitidea点击:

How to Disable Android LocationListener when application is closed

javaandroidlocation

提问by farissyariati

I have a class which handle a location service called MyLocationManager.java

我有一个处理名为 MyLocationManager.java 的位置服务的类

this is the code :

这是代码:

package com.syariati.childzone;

import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class MyLocationManager {

    private Context context;
    private double myLat = 0.0;
    private double myLon = 0.0;
    private LocationManager locationManager = null;
    private Location location = null;
    private Criteria criteria;
    private String locationName = null;

    public MyLocationManager(Context ctx) {
        this.context = ctx;
    }

    private String setCriteria() {
        this.criteria = new Criteria();
        this.criteria.setAccuracy(Criteria.ACCURACY_FINE);
        this.criteria.setAltitudeRequired(false);
        this.criteria.setBearingRequired(false);
        this.criteria.setCostAllowed(true);
        this.criteria.setPowerRequirement(Criteria.POWER_LOW);
        return locationManager.getBestProvider(criteria, true);
    }

    public double getMyLatitude() {
        return this.myLat;
    }

    public double getMyLongitude() {
        return this.myLon;
    }

    public String getLocation() {
        return this.locationName;
    }

    public void onLocationUpdate() {
        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        String provider = setCriteria();

        location = locationManager.getLastKnownLocation(provider);
        updateWithNewLocation(location);
        locationManager.requestLocationUpdates(provider, 1000, 0,
                new MyLocationListener());

    }

    private void updateWithNewLocation(Location location) {
        if (location != null) {
            this.myLat = location.getLatitude();
            this.myLon = location.getLongitude();
//          Toast.makeText(this.context,
//                  "Lokasi Anda:\n" + this.myLat + "\n" + this.myLon,
//                  Toast.LENGTH_LONG).show();
            getLocationName(this.myLat, this.myLon);
        } else {
            Toast.makeText(this.context, "Lokasi Anda Tidak Diketahui",
                    Toast.LENGTH_SHORT).show();
        }
    }

    private void getLocationName(double lat, double lon) {
        Geocoder geocoder = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> adresses = geocoder.getFromLocation(lat, lon, 1);
            StringBuilder sb = new StringBuilder();
            if (adresses.size() > 0) {
                Address address = adresses.get(0);
                for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
                    sb.append(address.getAddressLine(i)).append("\n");
                sb.append(address.getCountryName()).append("\n");
            }
            this.locationName = sb.toString();
//          Toast.makeText(context, sb.toString(), Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location newLocation) {
            // TODO Auto-generated method stub
            myLat = newLocation.getLatitude();
            myLon = newLocation.getLongitude();
            getLocationName(myLat, myLon);
            Toast.makeText(context,
                    "Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
                    Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onProviderDisabled(String arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // TODO Auto-generated method stub
        }

    }

}

which has an Inner class that implements location listener on it. So far, it works. It listen the location with no problem. However, when I exit my apps, it doesn't completely stop the listen the location. As you see from this code :

它有一个在其上实现位置侦听器的 Inner 类。到目前为止,它有效。它可以毫无问题地收听位置。但是,当我退出我的应用程序时,它并没有完全停止收听位置。正如您从这段代码中看到的:

@Override
            public void onLocationChanged(Location newLocation) {
                // TODO Auto-generated method stub
                myLat = newLocation.getLatitude();
                myLon = newLocation.getLongitude();
                getLocationName(myLat, myLon);
                Toast.makeText(context,
                        "Lokasi terupdate\nLat: " + myLat + "\nLon: " + myLon,
                        Toast.LENGTH_SHORT).show();
            }

while the location is updated, the toast will be shown, and it still appear when the location is updated. Even when I've closed the application.

当位置更新时,toast 将显示,并且在位置更新时它仍然出现。即使我关闭了应用程序。

How to stop the location listener completely in my case.

在我的情况下如何完全停止位置侦听器。

This one helped me to stop the updat :

这个帮助我停止更新:

android how to stop gps

android如何停止gps

采纳答案by PhatHV

You may call removeUpdates on your LocationManager.

您可以在 LocationManager 上调用 removeUpdates。

public void removeUpdates (PendingIntent intent)

Removes any current registration for location updates of the current activity with the given PendingIntent. Following this call, updates will no longer occur for this intent.

Parameters:

intent {#link PendingIntent} object that no longer needs location updates

Throws:

IllegalArgumentException if intent is null

public void removeUpdates(PendingIntent 意图)

使用给定的 PendingIntent 删除当前活动的位置更新的任何当前注册。在此调用之后,将不再针对此意图进行更新。

参数:

不再需要位置更新的意图 {#link PendingIntent} 对象

抛出:

如果 Intent 为 null,则为 IllegalArgumentException

See here: http://developer.android.com/reference/android/location/LocationManager.html#removeUpdates(android.app.PendingIntent)

请参阅此处:http: //developer.android.com/reference/android/location/LocationManager.html#removeUpdates(android.app.PendingIntent)

Updated:

更新:

In this case, you may change this line:

在这种情况下,您可以更改此行:

locationManager.requestLocationUpdates(provider, 1000, 0,
                new MyLocationListener());

to:

到:

MyLocationListener myLL = new MyLocationListener();
locationManager.requestLocationUpdates(provider, 1000, 0,
                myLL);

When you want to remove your listener call as below:

当您想删除您的侦听器调用时,如下所示:

locationManager.removeUpdates(myLL);