【问题标题】:Keep calling function and show progress bar until returned true?继续调用函数并显示进度条直到返回true?
【发布时间】:2014-09-18 12:22:52
【问题描述】:

我需要运行这段代码直到它工作,

LatLng current_pos = new LatLng(location.getLatitude(), location.getLongitude());
cp.SetCoordsCurrent(current_pos);

我注意到如果信号良好,它可以正常工作,但如果信号很弱,则应用程序崩溃或抛出异常(使用 try 和 catch)。 如何运行此代码直到它获得坐标?我还需要在尝试修复时显示进度条。

【问题讨论】:

    标签: android google-maps


    【解决方案1】:

    你的问题不够清楚,所以不是确切的答案,但试试这个:

    AsyncTask 中移动获取坐标的代码并在doInBackground() 中执行任务,在 preExecute 中显示进度对话框,在 postExecute 中隐藏该进度对话框,并检查坐标是否已获取并设置坐标。

    在此处阅读有关 AsyncTask 的更多信息:http://developer.android.com/reference/android/os/AsyncTask.html

    【讨论】:

    • 这不太行,我有使用 AsyncTask 的地理编码器,但这是用于获取实际地址名称,而我发布的功能是从 LocationListener 获取当前原始坐标
    【解决方案2】:

    为什么不把它放在while 循环中?

    while (true) {
        try {
    
            // If this throws any exception, then the `break` will 
            // be ignored and it jumps to `catch` clause.          
            LatLng current_pos = new LatLng(location.getLatitude(), location.getLongitude());
            cp.SetCoordsCurrent(current_pos);
    
            // If we get this far, then there was no exception
            // and we have the location. So we break the loop.
            Log.d("TAG", "Got the signal");
            break;
    
        } catch (Exception e) {
            Log.d("TAG", "Still weak signal" );
        }
    }
    

    【讨论】:

    • 这导致冻结,一两分钟后android开始响应它并终止了活动。也许有一种方法可以在后台线程而不是在 UI 线程上运行它,并且虽然它没有获取位置 - 显示进度对话框?如果是这样,那是怎么做的?
    • @arleitiss,这正是 Shumail 所解释的。把它放在 AsyncTask 的 doInBackground() 方法中。所以它会在另一个线程中运行。
    • 是的,但就是这样,它与任何 AsyncTask 无关,它是来自 locationManager 的直接调用,我使用 AsyncTask 的唯一地方是让 GeoCoder 获取特定地址。还是我错误地认为 AsyncTask 仅用于网络线程(与 http 相关的操作)?
    • @arleitiss,AsyncTask 只是线程的简化版本,它可以促进一切。它适用于需要在另一个线程上完成的任何类型的操作。所以你可以使用它。
    • 我意识到我的错误,它无法完成 while 循环,因此它永远卡在其中,因为:我的 LocationManager 以及 Location 是静态的,因为它只被调用和更新一次 Activity开始,因此如果活动在位置不可用时开始 - 它将保持不变。现在我将 AsyncTask 参数从 Location 修改为 LocationManager,因此它会在 while 循环中不断更新 LocationManager。因此,一旦 LocationManager 收到 Current Location = while 完成并且 ProgressDialog 关闭。只是一个我没有考虑过的简单而愚蠢的错误。
    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 2014-03-27
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多