如何让Android等待? [英] How to make Android wait?

查看:193
本文介绍了如何让Android等待?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,需要在GPS启用后立即接收用户的纬度和经度...我正在使用onGpsStatusChanged来不断检查GPS状态,并且检查工作正常...唯一的问题是,它试图立即检索用户位置,它返回纬度0.0和经度0.0,导致获取这些信息需要花费几秒钟的时间...如果我稍后尝试在按钮上使用clickListener检索几秒钟,则效果很好.

In my program, it is needed to receive user latitude and longitude as soon as GPS is Enabled... I'm using onGpsStatusChanged to constantly check GPS Status and the checking works... The only problem is that it tries to retrieve user location instantly, and it returns latitude 0.0 and longitude 0.0 cause it takes some seconds to get those informations... If I try to retrieve some seconds later using clickListener on a button it works perfectly...

然后我想:如果我可以使设备在启用GPS后 稍等几秒钟,然后再获取坐标,它将起作用...

Then I thought: If I could make the device wait some seconds after GPS is Enabled and only then retrieve the coordinates it would work...

但是:如果我使用另一个Thread或AsyncTask(都尝试过这两个方法),它会一直返回0.0的坐标,这是因为实际的坐标已缓存到 Map的Main Activity 线程中...

But: If I use another Thread or AsyncTask (already tried both), it keeps returning 0.0 for coordinates, cause the real coordinates are cached into the Map's Main Activity Thread...

那么,如何让android在主线程中等待?我尝试了"wait(long)",应用程序崩溃了.我试图解决这个问题长达数周,而我的时间却用光了……请一些圣灵帮助我

So, how to make android wait in the main Thread? I've tried 'wait(long)' and the app crashes. I'm trying to solve this for weeks and my time is running out... Some holy soul help me please

推荐答案

您可以通过使用处理程序

you can achieve that by using handler

int time=3000 // in milliseconds

      Handler h=new Handler();

      h.postDelayed(new Runnable() {

         @Override
        public void run() {

         //here you can do the job

          }

        },time);

如果您想从处理程序中更新UI,则会导致错误,但可以使用runOnUiThread

if you want to update the UI from the handler you will end up with an error but you can userunOnUiThread

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        //code to update the ui
    }
});

祝你好运

这篇关于如何让Android等待?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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