安卓GPS回调关闭UI线程 [英] Android GPS Callback off UI Thread

查看:175
本文介绍了安卓GPS回调关闭UI线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获得GPS的onLocationChanged到在不同的线程中运行。我理解如何管理用户界面线程,当我打电话功能,但与GPS,我不会主动调用该函数。

I'm having trouble getting the GPS's onLocationChanged to run on a different thread. I understand how to manage UI thread when I'm calling a function but with the GPS, I don't actively call the function.

我的意图是每次GPS接收阅读时间有一道光闪过。我已经把这个功能在一个Runnable。我通过这个函数来实现LocationListener的一类。然后在主类,我开始一个新的线程调用requestLocationUpdates。我希望在LocationListener的的onLocationChanged会在不同的线程中运行,后期回调,并在UI线程必要的UI效果。不幸的是,程序崩溃每次试图调用requestLocationUpdates时间。什么是这样做的正确方法?

My intent is to have a light flash every time the GPS receives a reading. I have put this function in a Runnable. I passed this function to a class that implements LocationListener. Then in the main class, I started a new thread that calls requestLocationUpdates. I was hoping that onLocationChanged of the LocationListener would run in a different thread, post to the callback and make the necessary UI effects in the UI thread. Unfortunately, the program crashes every time it tries to call requestLocationUpdates. What's the proper way of doing it?

现在,它看起来像这样

主要类:

final Runnable changeLight = new Runnable(){
        public void run(){
            // do stuff
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.capture);

        status = (ImageView) findViewById(R.id.status);
        database = new DatabaseManager(this);

        new Thread(){
            public void run(){
                location = (LocationManager) getSystemService(LOCATION_SERVICE);
                listener = new GPSManager(database, changeLight, light, status);
                location.requestLocationUpdates("gps", 10000L, 0, listener);
            }
        }.start();
    }

LocationListener的类:

LocationListener class:

public void onLocationChanged(Location location) {
        if (location.getAccuracy() <= 32.0){
            light = lightColors.Green;
            status.post(callback);
            database.insertData(location);
        }
        else{
            light = lightColors.Yellow;
            status.post(callback);
        }
    }

例外称无法创建处理程序中的线程并没有所谓的活套。prepare()

The exception says Can't create handler inside thread that has not called Looper.prepare()

推荐答案

在您调用location.requestLocationUpdates必须有一个活套螺纹(见<一href="http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29"相对=nofollow>这里)。 你可以用它代替螺纹HandlerThread。

The thread where you call location.requestLocationUpdates must have a Looper ( see here ). You can use HandlerThread instead of Thread.

这篇关于安卓GPS回调关闭UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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