android while循环替代 [英] android while loop alternative

查看:51
本文介绍了android while循环替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的第一个 Android 应用程序,我发现 while 循环有问题,我试图在我的 Android 应用程序上使用 while 循环,但应用程序死机.

This is my first Android application and I am finding troubles with while loop, I am trying to use a while loop on my Android application but the application freezes.

我要做的是跟踪用户位置(使用 onlocationChanged)并继续查询该位置,直到查询返回结果.这是一个 GIS 应用程序,所以我将描述应用程序的行为:应用程序使用侦听器onLocationChangedListener"持续跟踪用户位置并将其存储在变量myPosition"中.我正在使用布尔值noResults=true".我将在 while 循环中使用一个方法query(myPosition)",这个方法有一个回调,当找到结果时,将布尔值noResults"更改为false.循环将一直持续到noResults"为假(这意味着查询的回调更改了布尔值)

What I'm trying to do is track the user location (using onlocationChanged) and keep querying on the location until the query returns a result. It's a GIS application so I am going to describe the application behavior: the application keeps tracking the user position using a listener "onLocationChangedListener" and store it in a variable "myPosition". I am using a boolean"noResults=true". I will use a method "query(myPosition)" in the while loop, this method has a callback that when a result is found, and changes a boolean "noResults" to false. the loop will keep on until "noResults" is false (that means query's callback changed the boolean's value)

,这是我所做的:

while(noResults)
{
//myPosition keeps changing 
      query(myPosition);
//query has a callback that when a result is found it changes noResults to false
}

推荐答案

在主线程上运行 while 循环代码会冻结 UI,并使所有其他进程暂停,从而使您的应用程序无响应使用

running while loop codes on the main thread freezes the UI, and makes all other processes pause making your app unresponsive use

Threads..

还请注意,您正在运行的 while 循环是在称为 ui 线程的默认线程上运行的,因此在短期内,while 循环会在单独的线程上运行.例如...

also note that the while loop you are running is running on a default Thread termed as the ui thread so in short run while loops on separate threads.. eg..

new Thread(new Runnable() {

    @Override
    public void run() {
    // Your hard while loop here
    //get whatever you want and update your ui with ui communication methods.
    }
).start();

用于 ui 通信方法

View.post(new Runnable() {

    @Override
    public void run() {
    // TODO Auto-generated method stub
    Toast.makeText(getActivity(), "updated ui", Toast.LENGTH_LONG).show();
    }
});    

视图可以是您正在更新的任何视图.也像@TehCoder 说你可以使用 asynctask 但 asynctask 不适合长时间的工作流工作,其中有 3 个,但我不记得最后一个

the view could be any views you are updating.. also like @TehCoder said you could use asynctask but asynctask is not meant for long workaflow work there are 3 of them but i can't recall the last one

这篇关于android while循环替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆