我有一個AsyncTask
,它調用我的LocationHandler
類方法getLocation()
,它也運行Thread
。我收到以下錯誤:調用一個包含AsyncTask線程的方法(不想調用Looper.prepare())
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);
}
我將如何將它集成到我的代碼? – Neeta 2012-01-06 13:04:55
我真的不確定,也許試着用你的HandlerThread做些什麼? – goodm 2012-01-06 13:20:03