android - 无法将处理程序和可运行对象放置在 OnLocationChanged() 内

标签 android timer gps handler runnable

我已经计算了车辆的速度,并将该速度与某个阈值(即 speed<=3 )进行比较,现在的问题是计算等待时间。 我正在尝试计算车辆的等待时间,如果汽车停留超过两分钟,则等待超过两分钟后的总时间将被添加到等待时间中。我在 onLocationchanged() 中使用了处理程序和可运行程序 但我的时间计算是随机的。不同的处理程序和可运行对象同时运行,并且时间比定义的时间快。

@Override
public void onLocationChanged(Location location) {
    diaplayViews();


    timeGpsUpdate = location.getTime();
    float delta = (timeGpsUpdate - timeOld) / 1000;


    if (location.getAccuracy() <100) {

        distance += locationOld.distanceTo(location);


        Log.e("location:", location + "");




        speed = (long) (distance / delta);


        if(speed<=3)

        {
            if(runable==null)
            {


             runnable = new Runnable() {

                public void run() {
                    waitingTime++;
                    updateHandler.postDelayed(this, 10000); // determines the execution interval waiting time addition on every 10 seconds after 2 minutes initially

                }

            };}

            updateHandler.postDelayed(runnable, 60*2*1000); // acts like the initial delay
        }
        else {
            handler.removeCallbacks(runable);

            runable=null;
        }

        locationOld = location;
        timeOld = timeGpsUpdate;
        diaplayViews();

    }

}

最佳答案

使用 if(location.getspeed()==0.0) 并每 10 秒运行一次处理程序,最初添加两分钟(2*60),其他时间继续添加该时间,即 10 秒,最后除以 60 。 你会得到 最好的方法是使用服务,它将在后台运行程序并使用广播接收器来通知用户或在 UI 中显示结果。 http://developer.android.com/guide/components/services.html 对于广播接收器 http://developer.android.com/reference/android/content/BroadcastReceiver.html

关于android - 无法将处理程序和可运行对象放置在 OnLocationChanged() 内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34587359/

相关文章:

php - 寻找可靠的方法来了解我的手机是否在家

html - 是否有 html "location"元素?

android - BitmapFactory 无法对 CipherInputStream 解码两次

android - 将 APK 上传到 Android Market 时出现 minSdkVersion 错误

c# - Windows 服务定期产生一个线程到最大值

java - 使用微调器更改值

android - 模拟器控制被真正的安卓设备禁用

java - Android 应用程序在 for 循环后崩溃

android - 无法更改按钮的 IsEnabled 状态

c# - 设备进入休眠状态后 C# 计时器是否继续计数?