Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active December 13, 2018 18:00
Show Gist options
  • Select an option

  • Save wszdwp/daa22296d59aac31a76b7a7acb0dcf83 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/daa22296d59aac31a76b7a7acb0dcf83 to your computer and use it in GitHub Desktop.
handlerThread example
// start action when thread start
HandlerThread handlerThread = new HandlerThread("printingThread") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
// TODO: my action
}
};
handlerThread.start(); // this will trigger onLooperPrepared
// thread communications using handler
// 1. In UI thread, send message to background thread with background thread's handler
// send message from ui thread to background thread
HandlerThread handlerThread = new HandlerThread("myThread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String value1 = bundle.getString("key1");
String value2 = bundle.getString("key2");
//TODO: my action
}
};
Message message = new Message(); // or handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key1", "value1");
bundle.putString("key2", "value2");
message.setData(bundle);
handler.sendMessage(message); // or handler.sendMessageDelayed(message, 1000);
// 2. In background thread, send message to UI thread with UI thread's handler
final Handler uiHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
boolean printComplete = bundle.getBoolean("printComplete", false);
if (!printComplete) {
Toast.makeText(getBaseContext(), "Printing receipt failed, please check bluetooth printer setup!", Toast.LENGTH_LONG).show();
}
}
};
HandlerThread handlerThread = new HandlerThread("printingThread") {
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
// TODO: my action
// send message back to ui thread after action completed
Message msg = new Message();
Bundle b = new Bundle();
b.putBoolean("printComplete", printComplete);
msg.setData(b);
uiHandler.sendMessage(msg);
}
};
handlerThread.start(); // this will trigger onLooperPrepared
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment