0

我有一个连接到互联网的安卓应用程序,可以实时对经纬度坐标进行反向地理编码。这会滞后于 UI,并可能导致它给出“不响应 - 强制关闭/等待”错误(正如预期的那样,不使用异步/线程处理程序!)

我已经实现了一个运行良好的异步任务(不再有 UI 滞后!),但是在 onLocationChanged 方法中设置的变量(将它们设置为纬度和经度)是无法访问的。我在其中执行此操作的类链接到另一个单独的类,该类传递变量并可以向包含反向地理编码地址的人发送短信。但是,由于使用 doinbackground 方法实现异步任务,我无法再发送我需要的内容。我不知道我是否可以更好地解释,我将提供示例代码。

public void onLocationChanged(Location loc){
    mylat = loc.getLatitude();
    mylong = loc.getLongitude();
}

/*
afaik, this is the code that does the internet stuff, that lags the 
UI.  If I put this in doinbackground, it cannot access mylat & my long, 
and the "loc.getLatitude" has to be done in the "onLocationChanged" 
method, which HAS to exist. If I leave the ListAddress code outside the 
doinbackground, everything works, BUT the UI will obviously lag.
*/
List<Address> addresses = geoCoder.getFromLocation(mylat,mylong, 1); 

谁能建议mylat = loc.getLatitude(); & mylat = loc.getLatitude();进入 doinbackground 方法的最佳方法?

4

2 回答 2

3
  1. 覆盖 AsyncTask 的构造函数并将 和 设置mylatmylong该类中的变量
  2. 或者直接将它们传递给 doInBackground 方法。

    ... extends AsyncTask<Double, ProgressType, ReturnType> {
        protected ReturnType doInBackground(Double... params) {
            mylat = params[0];
            mylong = params[1];
            List addresses = geoCoder.getFromLocation(mylat, mylong, 1);
            ...
        }
        ...
    }
    

    并调用它execute(mylat, mylong);

于 2011-03-09T20:25:21.377 回答
1

您可以通过可以传递mylatmylong作为参数的方式覆盖 AsyncTask 类的构造函数。在构造函数中,将参数保存为 AsyncTask 的成员变量。这样做,您应该能够在 doInBackground() 方法中访问它们。

另一件事是,您应该考虑是否真的需要位置侦听器。如果您只需要特定时刻的当前位置,也许LocationManager及其方法getLastKnownLocation()也可以完成这项工作。然后,您还可以在 doInBackground() 方法中确定当前位置。但是,如果它真的符合您的需要,请阅读getLastKnownLocation()的文档。如果每次设备移动时都需要更新,则必须使用位置侦听器。

于 2011-03-09T20:05:01.520 回答