android - 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 不再更新。我究竟做错了什么?
解决方案
推荐阅读
- arduino - 附加中断频率arduino
- buddypress - Buddypress - 限制活动流上的博客摘录
- android - Android获取包含至少一个媒体文件(如照片/视频)的所有文件夹
- flutter - 我在 flutter 中遇到 findAncestorStateOfType 错误。我该怎么办?我被困在这里
- kotlin - 在 kotlin react 中编写自定义钩子
- neural-network - Pytorch 神经网络如何将数据集加载到 GPU 中
- google-cloud-endpoints - 通过谷歌云端点访问谷歌应用引擎rest api
- selenium - 如何找到附加屏幕截图的 xpath。在 Java 中会有帮助
- docker - 不存在图像标签时如何查看 docker 图像层
- r - discretizeDF.supervised(formula, data, method = disc.method) 中的错误:data 需要是 data.frame