First time ,i invoke HandlerThread.start() to handle the background service. after all the stuffs completed,I wanna to end this Thread by calling HandlerThread.quit().
Then the second time,I start this Handler,and checked the HandlerThread.isAlive(),the isAlive() return false, but when i invoke HandlerThread again by HandlerThread.start().
But I got the IllegalThreadStateException,why?
How can i really stop the HandlerThread before I invoke handlerThread.start() again safely?
onCreate(){
...............
CurrentLocationPresenter =
new CurrentLocationPresenter(getApplicationContext(),mHandler);
}
public void onClick(View v) {
int id = v.getId();
switch (id){
case R.id.showplacebutton:
showPlaceInMapActivity();
break;
case R.id.showgpsbutton:
if (mCurrentLocationPresenter.isAlive()){
break;
}
mCurrentLocationPresenter.start();
break;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == CurrentLocationPresenter.WHATCODE){
mCurrentLatlng = (LatLng) msg.obj;
mTextView.setVisibility(View.VISIBLE);
if (mCurrentLatlng!=null) {
mTextView.setText(mCurrentLatlng.toString());
}
mCurrentLocationPresenter.getLooper().quit();
}
}
};
As stated, you can never call the start/run/execute method on a thread object more than once, as you will get the IllegalThreadStateException.
You can, however, use something such as an ExecutorService which will allow you to use the same Runnable multiple times.
Also, if you use a ThreadPoolExecutor, which is a descendant of ExecutorService, the memory and thread management is taken care of.