如何管理活套和线程(线程不会死了!) [英] How to manage Loopers and Threads (thread doesn't die anymore!)

查看:144
本文介绍了如何管理活套和线程(线程不会死了!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类扩展Thread通过LocationManager在非UI线程来获取用户的位置。我实现了这个作为一个线程,因为它必须要求启动并完成其工作只是在有限的时间。 顺便说一句,我不得不添加一个活套对象中的线程,才能够创建处理程序LocationManager(onLocationChanged)。

I created a class extending Thread to retrieve user location through LocationManager in a non-ui thread. I implemented this as a thread because it has to be started on request and do its work just for a limited time. By the way, I had to add a Looper object in the thread, to be able to create the handler for the LocationManager (onLocationChanged).

这是在code:

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将不会收到新的位置)。

I would like the thread to start, receive the user location data (in this case just one time), send the data to the main thread via a message to the handler, and then die. The problem is that in my case the thread does not die anymore, once the run method ended (that should be fine, because otherwise onLocationChanged would not receive the new locations).

但这种方式,假设线程的停止和暂停的方法是去precated,这将是一个很好的方式,在这种情况下,至少使一个弯一个线程死掉?

But in this way, assuming that thread's stop and suspend methods are deprecated, what would be a good way, in this case at least, to make a thread with a looper die?

在此先感谢;)

推荐答案

您可以明确的尺蠖的循环使用退出处理程序

You can explicitly quit from Looper's loop using Handler:

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();
    }
}

这篇关于如何管理活套和线程(线程不会死了!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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