0

我在我的项目中面临一个非常愚蠢的问题,无法解决。我正在使用 AsyncTask 获取用户的当前位置。我使用一个计数器作为计时器。在 doInBackground 内部,我正在递增该计数器,如果它大于 x 值,则我取消异步任务。

这是代码片段: -

class CurrentPositionTask extends AsyncTask<String, Void, Void> {
        long counter = 0;
        boolean flag = true;

        @Override
        public void onPreExecute() {
            // TODO Auto-generated method stub
        }

        @Override
        public Void doInBackground(String... params) {
            // TODO Auto-generated method stub
            do {
                counter++;
                if (latitude != 0 && longitude != 0) {
                    flag = false;
                }
            } while (counter <= 100000);
            return null;
        }

        @Override
        public void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
        }

    }

但是这里的while条件不起作用。我也尝试了 for 循环而不是 while 但这对我也不起作用。也面临着非常奇怪的问题,当我使用 sysout 打印计数器时,它工作正常,但没有它就无法工作..

欢迎所有建议。

4

3 回答 3

4

这个循环

while (counter <= 100000 || flag);

will go on as long as any of the conditions hold, so it will continue while counter <= 10000 or flag is true. If flag is false but counter is less than 100000 it will continue. If you intend to terminate the loop when flag is false, then you need to do instead:

while (counter <= 100000 && flag);

Update: It seems from your comments that you expect the hundred thousand incrementation of the counter variable to take roughly 20-30 seconds. Current day processors are way faster than that. I won't even mention the speed variation between processors, because its negligible anyway. You can wait for real 30 seconds with this loop, though is a busy-waiting loop (just like your original intent) and not something nice to do:

final long startTime = System.currentTimeMillis();
do {
    ...
} while( System.currentTimeMillis() - startTime <= 30 * 1000 );
于 2012-06-09T06:24:54.553 回答
1

Time bound task can be done using the TimerTask. Check the following:

boolean timeExpired = false;

        @Override
        protected Void doInBackground(Void... params) {

            Timer t =new Timer();

            TimerTask tk = new TimerTask() {

                @Override
                public void run() {
                    timeExpired = true;
                }
            };

            t.schedule(tk, 500);

            while(!timeExpired){
                if (latitude != 0 && longitude != 0) {
                    t.cancel();
                    tk.cancel();
                    break;
                }
            }

            return null;
        }

Hope this helps.

于 2012-06-09T06:51:36.963 回答
0

Just use

Looper.prepare();

before while loop in doInBackground method

于 2017-04-02T07:28:33.347 回答