Skip to content Skip to sidebar Skip to footer

How Can I Pass Message Via Handler In Android?

I'm learning how work handler in Android. I did Android server and socket class. I want send some message (i.e. 'New Connect') from socket to mainactivity, when somebody connect to

Solution 1:

This is a sample of a bigger project I was involved a few years ago. You will not be able to run as it is, but I think you can see how the communication between a Service and an Activity works. Feel free to ask if anything is not clear

Service

publicclassBluetoothService {

   privatefinal Handler mHandler;

    publicBluetoothService(Context context, Handler handler) {

         mHandler = handler;
    }

    publicsynchronizedvoidConnecting(...) {

      ...

      MessageMenssageToActivity= mHandler.obtainMessage(Cliente_Bluetooth.MESSAGE_HELLO);
      Bundlebundle=newBundle();
      bundle.putString(BluetoothClient.DEVICE_NAME, " Gorkatan");
      MensajeParaActivity.setData(bundle);
      mHandler.sendMessage(MensajeParaActivity);

      ...

    }
}

Activity

publicclassBluetoothClient{

      publicstaticfinalintMESSAGE_HELLO=1;
      publicstaticfinalintMESSAGE_BYE=2;

      @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

            mBluetoothService = newBluetoothService(this, mHandler);
      }

      privatefinalHandlermHandler=newHandler() {

            @OverridepublicvoidhandleMessage(Message msg) {
                switch (msg.what) {


                case MESSAGE_HELLO:

                    StringmName=null; 
                    mName = msg.getData().getString(DEVICE_NAME);

                    Toast.makeText(getApplicationContext(), "Hello "+ mName, Toast.LENGTH_SHORT).show();

                break; 

                case MESSAGE_BYE:

                    System.out.println("Bye!")

                break;


}

Here it is the whole project (which has got comments and variable names in Spanish):

https://github.com/ignacio-alorre/PDF-Dispenser/tree/master/Client/Cliente_Bluetooth/src/com/cliente_bluetooth

Solution 2:

If you plan on sending data from a thread to your handler then use obtainMessage to create a message object.

You must also use the same instance of the handler to handleMessage and sendMessage.


Here you will find a great resource explaining how to use Handler:

https://www.youtube.com/watch?v=LJ_pUlWzGsc

Post a Comment for "How Can I Pass Message Via Handler In Android?"