描述:
问题:应用中的UI线程没有等待,它立即获得默认状态false
我在以下代码中出错了?
UI线程:
private void printingStatus()
{
if(printData.isPrintFinished())
// do something
else
// do something
}
//在不同的线程中执行打印的PrintData类
private boolean printFinished = false;
// UI thread asks this method whether printing is success or failure
public boolean isPrintFinished() {
return printed;
}
public void setPrintFinished(boolean printed) {
this.printed = printed;
}
public static interface IPrintFinished {
public void onPrintFinished(boolean success);
}
public void printData() {
sendDataToPrinter(context, contentToPrint, new IPrintFinished() {
@Override
public void setPrintFinished(boolean success) {
if (success) {
setPrintFinished(true);
Logger.e("inside if success - printed"+printed);
}
setPrintFinished(false);
Logger.e("printed outside if" + printed);
}
});
}
public static void sendDataToPrinter(final Context context, final contentDefinition contentToPrint, final IPrintFinished listener) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
// starts here the actual printing and gets a result
int tmpResult;
try {
DataPrinter.getInstance().print(contentToPrint);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Logger.e("exceptpion:" + e);
}
tmpResult = STATUS_PRINTED;
} catch (TechnicalException e) {
Logger.e("exceptpion:" + e);
if (e.getMessage() != null && DataPrinter.ERROR_BLUETOOH_IS_DISABLED.equals(e.getMessage()))
tmpResult = STATUS_BLUETOOTH_DISABLED;
else
tmpResult = STATUS_ERROR;
}
final int result = tmpResult;
Logger.e("print result:"+result);
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if(result == STATUS_PRINTED) {
if (listener != null) {
Logger.e("inside the listener status printed");
listener.onPrintFinished(true);
}
} else if (result == STATUS_BLUETOOTH_DISABLED) {
SimpleToast.showToast("bluetooth disabled");
if (listener != null) {
listener.onPrintFinished(false);
}
} else {
SimpleToast.showToast("cannot connect to printer");
if (listener != null) {
listener.onPrintFinished(false);
}
}
}
});
Looper.loop();
}
}).start();
}