This is an old revision of the document!
Handlers and Messaging
Passing a message to a function in another class
Function will process message in handler thread, not the main thread
// first we create the class and implement the callback interface public class GetMessageClass implements Handler.Callback { @Override public boolean handleMessage(@NonNull Message msg) { // parse the message using the message key Bundle bundle = msg.getData(); String string = bundle.getString("mykey"); Log.v("javademo3","got the message: " + string); return false; } }
Then in the main activity:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // after we have a class with a callback, we create a thread for the handler. // every handler has a looper which actually calls the handler: HandlerThread handlerThread = new HandlerThread("myHandlerThread"); handlerThread.start(); Looper looper = handlerThread.getLooper(); // create an instance of the class GetMessageClass getMessageClass = new GetMessageClass(); // create a new handler and assign it to the looper in the handler thread Handler handler = new Handler(looper, getMessageClass); // boilerplate to send a message Message msg = handler.obtainMessage(); // ? Bundle bundle = new Bundle(); bundle.putString("mykey", "hello"); msg.setData(bundle); handler.sendMessage(msg); } }