I have an AsyncTask which calls my LocationHandler class method getLocation() which runs a Thread as well. I’m getting the following error:
Can't create handler inside thread that has not called Looper.prepare()
Some answers have included calling Looper related methods but I’d rather not do this as it’s bad practise
Main Activity calls the 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, seems to crash when it calls 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);
}
I used @nininho suggestion but I called
Looper.prepare()just before I calledrequestLocationUpdates()in myLocationHandlerclass. I also had to callLooper.loop()just after I called theThreadotherwise theThreadwouldn’t even run.