У меня есть AsyncTask
, который вызывает мой LocationHandler
метод класса getLocation()
, который также запускает Thread
.Я получаю следующую ошибку:
Can't create handler inside thread that has not called Looper.prepare()
Некоторые ответы включают вызов Looper
связанных методов, но я бы не стал этого делать, так как это плохая практика
Main Activity вызывает 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);
}