如何在 AsyncTask 中获得速度?

How to get speed in AsyncTask?

我正在开发一款可为您提供两点之间平均速度的应用程序,但我找不到在单独的 AsyncTask 中分隔 "location logic" 的方法。 我必须检查你是否在两个(starting/finishing)点之一,然后将即时速度添加到列表中并计算每次平均值并显示它。我想使用 LocationListener,但如何在异步任务中使用它?

在 AsyncTask 中(我已经获得所有权限,在主 activity 中询问):

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 中看到了 "ready" 和 "done",但 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 的初学者,这是我的第一个 "big project"

您应该在位置侦听器本身内部执行异步任务并将这些行移出到主线程:

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 的内部 class 或者将其作为一个参数。