Android: 间隔调用方法获取最新的位置坐标

Android: Calling method in intervals to retrieve the latest location coordinates

嗨!我的 Mainactivity class 中有一个 locationlistener 和 manager,但我认为这是一个非常糟糕的解决方案,因为我希望在不同的 class 中使用位置功能,因为我希望 listener 持续到 Intents。

我只有大约 10 个小时的 Android 编程经验,所以这对某些人来说可能看起来很糟糕 ;)

主要Activity

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xxx);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    location = new RetrieveLocation(this);
    checkForPermission();
    ...


//I want this method to call location.getCoordinates() in 1 second intervals
public void updateMap()  {

        if (location.hasFoundLocation()) {
            enableButton();
            marker.setPosition(location.getCoordinates());
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(location.getCoordinates(), 16));

        }
        else {
            disableButton();
        }
}


public void checkForPermission()
{

    if (Build.VERSION.SDK_INT >= 23) {
        ActivityCompat.requestPermissions(this, new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
        }, 10);
    }
    else {
        location.listen();
        updateMap();
    }
}

所以 retrieveLocation class 基本上只是在移动设备时更新用户位置。

所以我想抓取坐标到 mainActivity class 每秒更新 Google 地图.

上的标记

检索位置

public class RetrieveLocation
{
private LocationManager locationManager;
private LocationListener locationListener;
private LatLng _location;
private Context context;
public RetrieveLocation(Context context)
{
    this.context = context;
    locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}


public void listen()
{
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            _location = new LatLng(location.getLatitude(), location.getLongitude());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            context.startActivity(intent);
        }
    };
    //noinspection ResourceType
    locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}

...

public LatLng getCoordinates()
{
    if(_location != null)
        return _location;
    else
        return new LatLng(0,0);
}

我在写这篇文章之前搜索了很多post

如果您希望您的侦听器持续执行意图,您应该从服务调用它并从那里订阅事件。在收到事件时,您还必须更新您的 UI.