对于一个项目,我需要一个应用程序,该应用程序可以在 WebView 中打开网页,同时跟踪用户位置,即使手机未处于 Activity 状态或前面有另一个应用程序也是如此。
我成功了,一切都正常。检索到位置并且服务器能够使用这些位置。
问题是,如果我在后台跟踪两个多小时后切换回应用程序,一切都会变慢,并且 Web View 中的响应时间非常糟糕。
位置服务似乎正在减慢应用程序的速度。在安装该服务之前,不存在此问题。我无法解释,是什么导致应用程序缺乏,也许有人可以帮助我。
这是我的位置服务的代码。它在 Webview 的 onCreate 中作为 Intent 被调用。位置被写入字符串缓冲区,然后上传到服务器。 (省略了一些空的覆盖函数)
public class MyLocationService extends Service {
double latService;
double lngService;
long timeService;
float accService;
long oldtime;
String hash = "";
String buffer = "";
private LocationManager lm;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
LocationUpdates();
if ((timeService > 0) && (oldtime != timeService)) {
oldtime = timeService;
if (buffer.equals("")) {
buffer += latService + "," + lngService + "," + accService + "," + timeService;
} else {
buffer += ";" + latService + "," + lngService + "," + accService + "," + timeService;
}
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("d", buffer);
client.post("server.php", params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int arg0, Header[] arg1, String arg2) {
System.out.println(arg2);
buffer = "";
}
});
}
handler.postDelayed(this, 15000);
}
};
handler.postDelayed(r, 10);
return Service.START_NOT_STICKY;
}
public void LocationUpdates() {
locListener locList = new locListener();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locList);
}
public class locListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
latService = location.getLatitude();
lngService = location.getLongitude();
timeService = Math.round(location.getTime() / 1000);
accService = location.getAccuracy();
}
}
}
预先感谢您的帮助。
最佳答案
我强烈建议使用Fused location provider PRIORITY_BALANCED_POWER_ACCURACY:
LocationRequest request = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
.setInterval(POLLING_INTERVAL)
.setFastestInterval(POLLING_INTERVAL/2)
.setSmallestDisplacement(MIN_INTERVAL_METERS);
它旨在为您提供 40 米范围内的精度,电池消耗 <= 0.6%/小时。
另请记住在不再需要时立即关闭位置监听。
关于java - 位置跟踪服务会减慢应用程序速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25365033/