从AsyncTask调用包含Thread的方法(不想调用Looper.prepare())

时间:2012-01-06 12:26:56

标签: android multithreading android-asynctask

我有一个AsyncTask调用我的LocationHandler类方法getLocation(),该方法也运行Thread。我收到以下错误:

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

有些答案包括调用Looper相关方法,但我不愿意这样做,因为这是不好的做法

主要活动调用AsyncTask:

public class Main extends Activity {        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        StartProcess sProcess = new StartProcess();
        sProcess.execute(this);
    }
}

的AsyncTask:

public class StartProcess extends AsyncTask<Main, Void, Void>
{
    @Override
    protected Void doInBackground(Main... params) {
        LocationHandler lh = new LocationHandler();
        try {
            lh.getLocation(null, params[0]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }
}

LocationHandler,在调用requestLocationUpdates():

时似乎崩溃了
public class LocationHandler {
    LocationManager mlocManager;
    MyLocationListener mlocListener;
    Location location;

    public synchronized void getLocation(final View view, final Main main) throws InterruptedException
    {   
        mlocManager = (LocationManager)main.getSystemService(Context.LOCATION_SERVICE);
        mlocListener = new MyLocationListener();
            Looper.prepare();
        mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 5000, 1, mlocListener);
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 1, mlocListener);


        Thread uiThread = new HandlerThread("UIHandler"){
            public synchronized void run(){

                //stuff
                }

            }

        };
        uiThread.start();

    } 

LocationListener的:

public class MyLocationListener implements LocationListener
{
    @Override
    public void onLocationChanged(Location loc)
    {

        location = new Location(loc);

    }

3 个答案:

答案 0 :(得分:1)

我不知道我是否做得对,但在我的一个功能中我只是添加这样的东西:  mHandler = new Handler(Looper.getMainLooper()); ,它有所帮助。

答案 1 :(得分:1)

由于HandlerThread编译器正在抱怨,只需在使用HandlerThread之前调用Looper.prepare()

答案 2 :(得分:0)

我使用了@nininho建议,但在我Looper.prepare()课程中调用requestLocationUpdates()之前,我就致电LocationHandler。我打电话给Looper.loop()之后我也不得不拨打Thread,否则Thread甚至都不会。