首页 > 解决方案 > Android:在后台获取gps位置

问题描述

当应用程序没有焦点(在后台运行)时,我想检索 GPS 位置。以下代码在应用程序获得焦点时工作正常,但在应用程序未获得焦点时停止接收 gps 更新。

服务等级:

public class GpsTracker extends Service
{

private final LocalBinder mBinder = new LocalBinder();
protected Handler handler;

LocationManager locationManager = null;

public class LocalBinder extends Binder {
    public GpsTracker getService() {
        return GpsTracker.this;
    }
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler = new Handler();

    final Context context = this;
    if(locationManager == null) {
        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener());
    }

    AsyncTask.execute(new Runnable() {
        @Override
        public void run() {
            try {
                locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    return Service.START_STICKY;
}


@Override
public IBinder onBind(Intent arg0) {
    return mBinder;
}

}

此类从 MainActivity 开始,如下所示:

Intent intent = new Intent(context, GpsTracker.class);
bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
startService(intent);

当应用程序最小化时,AsyncTask 仍然执行,但检索到的 Location 不再更新。我究竟做错了什么?

标签: androidgpslocationmanager

解决方案


推荐阅读