如何在AsyncTask中提高速度?

问题描述 投票:0回答:1

我正在开发一个可为您提供两点之间平均速度的应用程序,但是我找不到在单独的AsyncTask中分离“位置逻辑”的方法。我必须检查您是否在两个(起点/终点)之一中,然后将瞬时速度添加到列表中,并计算每次平均值并显示它。我想使用LocationListener,但是如何在异步任务中使用它?

在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的初学者,这是我的第一个“ big project”

java android android-asynctask android-gps
1个回答
0
投票

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

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
         }
    }

...

CalculationsTask

 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的内部类,或仅将其作为参数传递。

© www.soinside.com 2019 - 2024. All rights reserved.