我正在开发一个为您提供两点之间平均速度的应用程序,但是我找不到在单独的AsyncTask中分离“位置逻辑”的方法。
我必须检查您是否处于两个(起点/终点)之一,然后将瞬时速度添加到列表中,并在每次平均值时进行计算并显示出来。我想使用LocationListener,但是如何在Async任务中使用它呢?
在AsyncTask中(我已经拥有主要活动中要求的所有权限):
protected String doInBackground(Integer... integers) {
Looper.prepare();
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG,"READY");
Log.d(TAG,locationListener.);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, gpsInterval, 0, locationListener);
Log.d(TAG,"DONE");
return "";
}
我在logcat中看到“就绪”和“完成”,但myLocationListener没有任何显示
public class MyLocationListener implements LocationListener {
private static final String TAG = "MyLocationListener ";
private MySpeedList speedList= new MySpeedList();
@Override
public void onLocationChanged(Location location) {
Log.d(TAG,Float.toString(location.getSpeed()));
speedList.add(location.getSpeed());
Log.d(TAG,Float.toString(speedList.getAverageSpeed()));
}
...
有人有建议吗?我是学生,所以我是android的初学者,这是我的第一个“大项目”
最佳答案
您应该在位置侦听器内部执行异步任务,并将以下行移至主线程:
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
Log.d(TAG,"READY");
Log.d(TAG,locationListener.);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, gpsInterval, 0, locationListener);
Log.d(TAG,"DONE");
return "";
在您的听众中:
public class MyLocationListener implements LocationListener {
private static final String TAG = "MyLocationListener ";
private MySpeedList speedList= new MySpeedList();
@Override
public void onLocationChanged(Location location) {
if (calculationsTask == null || calculationsTask.getStatus() == AsyncTask.Status.FINISHED) {
calculationsTask = new CalculationsTask()
calculationsTask.execute(location);
} else {
// buffer pending calculations here or cancel the currently running async task
}
}
...
计算任务
private class CalculationsTask extends AsyncTask<Location, Integer, Long> {
protected Long doInBackground(Location location) {
// do calculations here
return speed;
}
protected void onPostExecute(Long result) {
// this method is executed in UI thread
// display result to user
}
}
在这里,您可以通过
onPostExecute(...)
方法传递计算结果,因为该方法在主线程上运行。另请注意,您无法第二次执行异步任务,因此您每次都必须创建一个新实例。此外,如果要在异步任务中访问
speedList
,则可以将CalculationsTask
设置为MyLocationListener
的内部类,或仅将其作为参数传递。