如何在requestLocationUpdates中使用Looper?

时间:2018-02-03 17:47:24

标签: java android android-studio android-looper

我是Android开发的初学者。我创建了一个小应用程序,可以在设备达到一定速度后拍照。但是,requestLocationUpdates方法的一个参数(当然用于跟踪用户的位置)在第三个参数中需要一个Looper。我该如何制作一个活套?它应该去哪里?我的requestLocationUpdates方法目前看起来像这样:(我用null代替Looper)

app.subscriber.object_transformer_elastica:
    class: AppBundle\EventSubscriber\ElasticaTransformSubscriber
    arguments: ["@fpn_tag.tag_manager"]
    tags:
        - { name: kernel.event_subscriber }

Android开发网站建议做这样的事情:

 protected void requestUpdates() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            MC.requestLocationUpdates(locRequest, mLocationCallback, null);
        }
    }

但是,我仍然不知道在哪里放置这段代码,一旦我把它放进去怎么办,或者我如何在我的MainActivity中使用它。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

正如@Markus在评论中所说,如果this已经实施Activity界面,您可能需要通过LocationListener。这是您需要的第三个参数,而不是Looper

答案 1 :(得分:0)

通过以下代码创建looper。

    HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
    handlerThread.start();
    // Now get the Looper from the HandlerThread
    // NOTE: This call will block until the HandlerThread gets control and initializes its Looper
    Looper looper = handlerThread.getLooper();

并将requestLocationUpdates()中的looper对象作为peramiter传递如下。

MC.requestLocationUpdates(locRequest, mLocationCallback, looper); 

答案 2 :(得分:0)

如果您的回叫无法访问磁盘且速度很快,则可以通过null

引用documentation,您应该通过

  

一个Looper对象,其消息队列将用于实现回调机制,或null以在调用线程上进行回调

如果你在主线程上调用requestLocationUpdates并将null作为Looper传递,那么你将在主线程上收到回调。

您无法从主线程访问网络,也不应在主线程上执行任何I / O操作。你的UI会开始滞后。

相关问题