Handler usage Summary of Android [i]

Source: Internet
Author: User

With Google's own Bluetooth chat example, the example has three source files, namely: Bluetoothchat.java, Devicelistactivity.java, Bluetoothchatservice.java.

Where Bluetoothchat.java is the main UI Activity,devicelistactivity.java is the pairing device list selection UI Activity,bluetoothchatservice.java is the function class contains multiple

The definition of the thread.

1. The handler member variable mhandler is defined in the main UI:

//The Handler that gets information back from the BluetoothchatservicePrivate Final Handler Mhandler=NewHandler () {@Override Public voidhandlemessage (Message msg) {Switch(msg.what) { CaseMessage_state_change:if(D) log.i (TAG, "Message_state_change:" +msg.arg1); Switch(MSG.ARG1) { CaseBluetoothChatService.STATE_CONNECTED:setStatus (getString (r.string.title_connected_to, Mconnectedd                    Evicename));                    Mconversationarrayadapter.clear ();  Break;  CaseBluetoothChatService.STATE_CONNECTING:setStatus (r.string.title_connecting);  Break;  CaseBluetoothchatservice.state_listen: CaseBluetoothChatService.STATE_NONE:setStatus (r.string.title_not_connected);  Break; }                 Break;  Case message_write:byte[] Writebuf = (byte[]) msg.obj; //construct a string from the bufferString Writemessage =NewString (WRITEBUF); Mconversationarrayadapter.add ("Me:" +writemessage);  Break;  CaseMessage_read:byte[] Readbuf = (byte[]) msg.obj; //construct a string from the valid bytes in the bufferString Readmessage =NewString (readbuf, 0, MSG.ARG1); Mconversationarrayadapter.add (Mconnecteddevicename+":  " +readmessage);  Break;  CaseMessage_device_name://Save the connected device ' s nameMconnecteddevicename =msg.getdata (). getString (Device_name); Toast.maketext (Getapplicationcontext (),"Connected to" +Mconnecteddevicename, Toast.length_short). Show ();  Break;  CaseMESSAGE_TOAST:Toast.makeText (Getapplicationcontext (), Msg.getdata (). getString (TOAST),                Toast.length_short). Show ();  Break; }        }    };

2. Initializes an instance of Bluetoothchatservice in the main UI and passes the Mhandler as a parameter to the instance at initialization time:

Private voidSetupchat () {log.d (TAG,"Setupchat ()"); //Initialize the array adapter for the conversation threadMconversationarrayadapter =NewArrayadapter<string> ( This, R.layout.message); Mconversationview=(ListView) Findviewbyid (r.id.in);        Mconversationview.setadapter (Mconversationarrayadapter); //Initialize the Compose field with a listener for the return keyMoutedittext =(EditText) Findviewbyid (r.id.edit_text_out);        Moutedittext.setoneditoractionlistener (Mwritelistener); //Initialize The Send button with a listener that for click eventsMsendbutton =(Button) Findviewbyid (r.id.button_send); Msendbutton.setonclicklistener (NewOnclicklistener () { Public voidOnClick (View v) {//Send a message using content of the edit text widgetTextView view =(TextView) Findviewbyid (r.id.edit_text_out); String message=View.gettext (). toString ();            SendMessage (message);        }        }); //Initialize the Bluetoothchatservice to perform Bluetooth connectionsMchatservice =New Bluetoothchatservice ( this , Mhandler); //Initialize the buffer for outgoing messagesMoutstringbuffer =NewStringBuffer (""); }

3. The event response function (send button) is defined in the main UI, which calls the SendMessage function:

// Initialize The Send button with a listener this for click eventsMsendbutton = (Button) Findviewbyid (r.id.but Ton_send); Msendbutton.setonclicklistener (new  Onclicklistener () {  publicVoid  OnClick (View v) {  //  Send a message using content of the edit text widget TextView    View == view.gettext (). toString ();  sendMessage (message); }});

4. In the SendMessage function, call the function class Bluetoothchatservice.java sub-function:

/*** sends a message. * @parammessage A string of text to send. */    Private voidsendMessage (String message) {//Check that we ' re actually connected before trying anything        if(Mchatservice.getstate ()! =bluetoothchatservice.state_connected) {Toast.maketext ( This, r.string.not_connected, Toast.length_short). Show (); return; }        //Check that there ' s actually something to send        if(Message.length () > 0) {            //Get the message bytes and the Bluetoothchatservice to write            byte[] Send =message.getbytes ();            mchatservice.write (send); //Reset out string buffer to zero and clear the Edit text fieldMoutstringbuffer.setlength (0);        Moutedittext.settext (Moutstringbuffer); }    }

Note here that the Mchatsercice.write (send) function, for thread-safety reasons, is defined in Bluetoothchatservice.java:

/*** Write to the connectedthread in an unsynchronized manner *@paramOut the bytes to write *@seeConnectedthread#write (byte[])*/     Public voidWritebyte[] out) {        //Create Temporary ObjectConnectedthread R; //Synchronize A copy of the Connectedthread        synchronized( This) {            if(mstate! = state_connected)return; R=Mconnectedthread; }        //Perform the Write unsynchronized R.write (out); }

This defines a temporary thread class Connectedthread R, and this thread class is defined as follows:

    /*** This thread runs during a connection with a remote device.     * It handles all incoming and outgoing transmissions. */    Private classConnectedthreadextendsThread {Private FinalBluetoothsocket Mmsocket; Private FinalInputStream Mminstream; Private FinalOutputStream Mmoutstream;  PublicConnectedthread (bluetoothsocket socket, String sockettype) {log.d (TAG,"Create Connectedthread:" +sockettype); Mmsocket=socket; InputStream Tmpin=NULL; OutputStream Tmpout=NULL; //Get the Bluetoothsocket input and output streams            Try{Tmpin=Socket.getinputstream (); Tmpout=Socket.getoutputstream (); } Catch(IOException e) {log.e (TAG,"Temp Sockets not created", E); } Mminstream=Tmpin; Mmoutstream=tmpout; }         Public voidrun () {log.i (TAG,"BEGIN Mconnectedthread"); byte[] buffer =New byte[1024]; intbytes; //Keep listening to the InputStream while connected             while(true) {                Try {                    //Read from the InputStreambytes =mminstream.read (buffer); //Send the obtained bytes to the UI ActivityMhandler.obtainmessage (Bluetoothchat.message_read, Bytes, 1, buffer). Sendtotarget (); } Catch(IOException e) {log.e (TAG,"Disconnected", E);                    Connectionlost (); //Start the service over to restart listening modeBluetoothchatservice. This. Start ();  Break; }            }        }        /*** Write to the connected OutStream. * @parambuffer the bytes to write*/         Public void Write(byte[] buffer) {            Try{mmoutstream.write (buffer); //Share the sent message back to the UI Activity                Mhandler. Obtainmessage (Bluetoothchat.message_write,-1,-1, buffer). Sendtotarget (); } Catch(IOException e) {log.e (TAG,"Exception during Write", E); }        }         Public voidCancel () {Try{mmsocket.close (); } Catch(IOException e) {log.e (TAG,"Close () of Connect socket failed", E); }        }    }

As can be seen from the definition of the WRITE () function,mhandler.obtainmessage (Bluetoothchat.message_write,-1,-1, buffer). Sendtotarget () The communication between the thread and the main UI is implemented.

Handler usage Summary of Android [i]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.