android - 如何管理 Looper 和线程(线程不会再死了!)

标签 android multithreading handler looper

我创建了一个扩展 Thread 的类,以在非 ui 线程中通过 LocationManager 检索用户位置。我将它实现为一个线程,因为它必须根据请求启动,并且只在有限的时间内完成它的工作。 顺便说一下,我必须在线程中添加一个 Looper 对象,以便能够为 LocationManager (onLocationChanged) 创建处理程序。

这是代码:

public class UserLocationThread extends Thread implements LocationListener {
//...
public void run() {
    try {
        Looper.prepare();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        Looper.loop();
        Looper.myLooper().quit();
    } catch (Exception e) {
        //...
    }
}

@Override
public void onLocationChanged(Location location) {
    locationManager.removeUpdates(this);
    //...
    handler.sendMessage(msg); //this is the handler for communication with father thread
}

//...}

我希望线程启动,接收用户位置数据(在本例中仅一次),通过向处理程序发送消息将数据发送到主线程,然后结束。 问题是,在我的例子中,一旦 run 方法结束,线程就不会再死掉(这应该没问题,否则 onLocationChanged 将不会接收到新位置)。

但是这样一来,假设线程的停止和挂起方法已被弃用,至少在这种情况下,使用循环器死掉线程的好方法是什么?

提前致谢;)

最佳答案

您可以使用Handler 显式退出Looper 的循环:

private Handler mUserLocationHandler = null;
private Handler handler = null;

public class UserLocationThread extends Thread implements LocationListener {    

 public void run() {
    try {
          Looper.prepare();
        mUserLocationHandler = new Handler();
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        Looper.loop();

    } catch (Exception e) {
        //...
    }
}


@Override
public void onLocationChanged(Location location) {
    locationManager.removeUpdates(this);
    //...
    handler.sendMessage(msg); 
    if(mUserLocationHandler != null){
        mUserLocationHandler.getLooper().quit();
    }
}

关于android - 如何管理 Looper 和线程(线程不会再死了!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6277953/

相关文章:

android - Google InApp Billing 空异常

ios - 如果我在 dispatch_async block 中有一个 dispatch_sync 调用,然后是第二个 dispatch 调用,那么第二个调用是同步还是异步有关系吗?

java - 使用 OnLongTouch 将图像移动到字符串

android - alarmManager 唤醒时更改 ImageView 资源

C# Windows 应用程序阻止 Windows 关闭/注销

java - 在路径 : DexPathList 上找不到类 "com.imagerecognition.MainActivity"

Android - 语音识别一个词?

android - 从适配器调用 fragment 方法

在队列为空之前调用join时的Python 3多处理队列死锁

WPF 应用程序消息循环和 PostThreadMessage