I use Executor [fixed thread pool] with my own ThreadFactory, which Looper adds:
Handler HANDLER = new Handler();
Executor THREADS = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
@Override public Thread newThread(Runnable runnable) {
return new MyThread(new Runnable() {
@Override public void run() {
Looper.prepare();
runnable.run();
}
});
}
});
private static class MyHandler extends Handler {
public boolean fail;
public void handleMessage(Message msg) {
switch(msg.what) {
case 1:
this.fail = msg.arg1 == 1;
Looper.myLooper().quit();
break;
}
}
}
}
, , , , . , . , Loop . (tryAgain). , , Looper.loop() ( ), ( ) :
THREADS.execute(new Runnable() {
private MyHandler myHandler = new MyHandler();
@Override public void run() {
boolean tryAgain = true;
while(tryAgain) {
try {
switch(request) {
[Handle network requests]
}
tryAgain = false;
} catch(IOException e) {
e.printStackTrace();
} finally {
if(tryAgain) {
HANDLER.post(new Runnable() {
@Override public void run() {
theAlertDialog.show();
}
});
Looper.loop();
tryAgain = !myHandler.fail;
}
}
}
}
});
AlertDialog OnClickListener:
DialogInterface.OnClickListener myOnclickListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Message msg = myHandler.obtainMessage(1);
msg.setTarget(this.handler);
msg.sendToTarget();
}
}
, - handler.getLooper().getThread().isAlive(), true, " ". , Message/Handler , ? .isAlive()? Android: -)