Andoran Tooth communication

Source: Internet
Author: User

Package Com.example.bluetoothtest;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.ioexception;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.io.OutputStream; Import Java.io.outputstreamwriter;import java.util.arraylist;import java.util.uuid;import android.app.Activity; Import Android.bluetooth.bluetoothadapter;import Android.bluetooth.bluetoothdevice;import Android.bluetooth.bluetoothserversocket;import Android.bluetooth.bluetoothsocket;import Android.content.broadcastreceiver;import Android.content.context;import Android.content.intent;import Android.content.intentfilter;import Android.os.bundle;import Android.os.handler;import Android.os.Message;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.TextView; Import android.widget.toast;/*** * * @author Zhang Zhang * */public class Mainactivity extends Activity {TextView t1,t2,t3; EditText et; Button But,but2,but3,but4,but5,but6,but7,but8,but9; Arraylist<bluetoothdevice>delist=new arraylist<bluetoothdevice> ();//Get output stream after connection OutputStream OutputStream; Bluetoothadapter bluetooth; String uuid= "a60f35f0-b93a-11de-8a39-08002009c666";//Uuidhandler Handler=new handler () for the service-side Bluetooth device {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); if (msg.what==-1) {Toast.maketext (Getapplicationcontext () , "Waiting for user to connect ...." ", 1). Show ();} if (msg.what==-2) {Toast.maketext (Getapplicationcontext (), "connected with user .... ", 1). Show ();} if (msg.what==-3) {Toast.maketext (Getapplicationcontext (), "Wait for the server to accept .... ", 1). Show ();} if (msg.what==-4) {Toast.maketext (Getapplicationcontext (), "The server has accepted .... ", 1). Show ();} if (msg.what==1) {Toast.maketext (Getapplicationcontext (), "Receive" + (String) msg.obj, 1). Show (); if (msg.what==2) {Toast.maketext (Getapplicationcontext (), "send" + (String) msg.obj, 1). Show ();}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); t1= (TextView) Findviewbyid (R.ID.T1); T2= (TexTView) Findviewbyid (R.ID.T2), t3= (TextView) Findviewbyid (R.ID.T3), et= (EditText) Findviewbyid (r.id.et); but= (Button) Findviewbyid (r.id.but); but2= (Button) Findviewbyid (R.ID.BUT2); but3= (Button) Findviewbyid (R.ID.BUT3); but4= (Button) Findviewbyid (R.ID.BUT4); but5= (Button) Findviewbyid (R.ID.BUT5); but6= (Button) Findviewbyid (R.ID.BUT6); but7= (button    ) Findviewbyid (R.ID.BUT7); but8= (Button) Findviewbyid (R.ID.BUT8); but9= (Button) Findviewbyid (R.ID.BUT9); Android phone may have more than one Bluetooth adapter, currently only use the default Bluetooth adapter, through this method can get to the default adapter Bluetooth=bluetoothadapter.getdefaultadapter ();// Enabling and disabling Bluetoothadapter is a time-consuming asynchronous operation that requires registering receiver monitor state changes Registerreceiver (new Myreceiver (), New Intentfilter ( bluetoothadapter.action_state_changed));//Call the StartDiscovery () method to turn on the device scan, Register the receiver to receive a scan status change (start scan or end scan) registerreceiver (new Searchreceiver (), New Intentfilter (Bluetoothadapter.action_ discovery_started)); Registerreceiver (new Searchreceiver (), New Intentfilter (Bluetoothadapter.action_discovery_ finished));//Call the StartDiscovery () method to turn on the device scan, register the receiver to receive the scanned device//through(Bluetoothdevice) Intent.getparcelableextra (bluetoothdevice.extra_device)//can obtain the scanned device Registerreceiver (new Searchdevicereceiver (), New Intentfilter (Bluetoothdevice.action_found)); But.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {if (Bluetooth.setname ( Et.gettext (). toString ())) {Toast.maketext (Getapplicationcontext (), "Set succeeded", 1). Show (); Elsetoast.maketext (Getapplicationcontext (), "Setup failed", 1). Show ();}); /Add <uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/> Permissions//After you can start the native Bluetooth adapter directly using the Enable () method, And you can modify the Bluetooth friendly name But2.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View arg0) { Bluetooth.enable ();}}); /Use the following statement to pop up the dialog box to see if it is on, the Onactivityresult () method gets the user option But3.setonclicklistener (new View.onclicklistener () {@ overridepublic void OnClick (View arg0) {Startactivityforresult (new Intent (bluetoothadapter.action_request_enable), 1 );}}); But4.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {if (bLuetooth.isenabled ()) {T1.settext ("address" +bluetooth.getaddress ()) T2.settext ("name" +bluetooth.getname ()); T3.setText ( "Visibility" +bluetooth.getscanmode ());} Elsetoast.maketext (Getapplicationcontext (), "Bluetooth Not Available", 1). Show ();}); /modify the native Bluetooth visible time But5.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View arg0) {Intent Intent =new Intent (bluetoothadapter.action_request_discoverable); Intent.putextra (Bluetoothadapter.extra_discoverable_ DURATION, Startactivityforresult (Intent, 2);}); But6.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {if (bluetooth.isenabled ( ) {delist.clear (); Bluetooth.startdiscovery ();}}); But7.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {createserver ();}}); But8.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {linktoserver ();}}); But9.setonclicklistener (New View.onclicklistener () {@Overridepublic void OnClick (View arg0) {send ();}});} private void LInktoserver () {try {Bluetoothdevice bluetoothdevice=delist.get (0); bluetoothdevice.getaddress (); final Bluetoothsocket Bluetoothsocket=bluetoothdevice.createrfcommsockettoservicerecord (UUID.fromString (UUID)); new Thread () {@Overridepublic void run () {try {handler.sendemptymessage ( -3); Bluetoothsocket.connect (); Handler.sendemptymessage ( -4); Outputstream=bluetoothsocket.getoutputstream (); GetInfo (Bluetoothsocket);} catch (Exception e) {e.printstacktrace ();}};}. Start ();} catch (Exception e) {e.printstacktrace ();}} Create a server-side, similar to socket programming private void Createserver () {try {final bluetoothserversocket btserver = Bluetooth.listenusingrfcommwithservicerecord ("Server", Uuid.fromstring (UUID)); new Thread () {@Overridepublic void Run () {try {while (true) {handler.sendemptymessage ( -1); final Bluetoothsocket serversocket = btserver.accept ();//Blocking method, Handler.sendemptymessage ( -2), Outputstream=serversocket.getoutputstream (), new thread () {///when there is a new connection, Give the new thread complete public void run () {getInfo (serversocket);};}. Start ();}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}};}. Start ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} private void Send () {String ss=et.gettext (). toString (). Trim (); try {bufferedwriter bw=new bufferedwriter (new OutputStreamWriter (OutputStream)); Bw.write (ss); Bw.newline ();//Note newline Bw.flush ();//flush Cache message Msg=new message (); Msg.obj=ss;msg.what=2;handler.sendmessage (msg);} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} private void GetInfo (Bluetoothsocket serversocket) {try {InputStream inputstream=serversocket.getinputstream (); BufferedReader br=new BufferedReader (New InputStreamReader (InputStream)); while (true) {String msg=br.readline (); Message msgs=new message (); Msgs.obj=msg;msgs.what=1;handler.sendmessage (msgs);}} catch (IOException e) {}} @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.on Activityresult (Requestcode, ResultCode, data); if (requestcode==1&&rESULTCODE==RESULT_OK) {Toast.maketext (Getapplicationcontext (), "Bluetooth enabled (Onactivityresult)", 1). Show (); if (requestcode==2&&resultcode!=result_canceled) {Toast.maketext (Getapplicationcontext (), "Bluetooth Visible Time Modified" + Requestcode+ "(Onactivityresult)", 1). Show ();}} Private class Myreceiver extends broadcastreceiver{@Overridepublic void OnReceive (Context arg0, Intent Intent) {int state =intent.getintextra (Bluetoothadapter.extra_state,-1); if (state==bluetoothadapter.state_turning_on) Toast.maketext (Getapplicationcontext (), "Bluetooth is on", 1). Show (); if (state==bluetoothadapter.state_on) Toast.maketext ( Getapplicationcontext (), "Bluetooth is turned on", 1). Show (); if (State==bluetoothadapter.state_turning_off) Toast.maketext ( Getapplicationcontext (), "Bluetooth is shutting down", 1). Show (); if (State==bluetoothadapter.state_off) Toast.maketext ( Getapplicationcontext (), "Bluetooth is Off", 1). Show ();}} Private class Searchreceiver extends broadcastreceiver{@Overridepublic void OnReceive (Context arg0, Intent Intent) {if ( BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals (Intent.getaction ()) {Toast.maketext ()) {Getapplicationcontext (), "Start discovery ... ", 1). Show ();} if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals (Intent.getaction ())) {Toast.maketext (getapplicationcontext (), "End of discovery ... ", 1). Show ();}}} Private class Searchdevicereceiver extends broadcastreceiver{@Overridepublic void OnReceive (Context arg0, Intent Intent ) {Et.append (Intent.getstringextra (bluetoothdevice.extra_name) + "\ n"); Toast.maketext (Getapplicationcontext (), Intent.getstringextra (Bluetoothdevice.extra_name), 1). Show (); try{ Delist.add ((Bluetoothdevice) Intent.getparcelableextra (Bluetoothdevice.extra_device)); Toast.maketext (Getapplicationcontext (), "Discovery Device", 1). Show (); catch (Exception e) {}}}}
The layout file is as follows
<pre name= "code" class= "HTML" ><scrollview xmlns:android= "Http://schemas.android.com/apk/res/android" xmlns:tools= "Http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "Match_ Parent "><linearlayout android:layout_width=" wrap_content "android:layout_height=" Match_parent "Android:o        rientation= "vertical" > <textview android:id= "@+id/t1" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "T1"/> <textview android:id= "@+id/t2" a Ndroid:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "T2"/> <TextV        Iew android:id= "@+id/t3" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"        android:text= "T3"/> <edittext android:id= "@+id/et" android:layout_width= "Fill_parent" android:layout_height= "Wrap_content"        /> <button android:id= "@+id/but" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" android:text= "set name"/> <button android:id= "@+id/but2" Android:layout_w Idth= "Wrap_content" android:layout_height= "wrap_content" android:text= "Auto Open"/> <button Android Oid:id= "@+id/but3" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:t Ext= "Prompt to open"/> <button android:id= "@+id/but4" android:layout_width= "Wrap_content" Android:lay out_height= "Wrap_content" android:text= "Get Info"/> <button android:id= "@+id/but5" Android:layo        Ut_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Modify visibility"/> <button Android:id= "@+id/but6" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android   oid:text= "Find Device"/> <button android:id= "@+id/but7" android:layout_width= "wrap_content" android:layout_height= "Wrap_co Ntent "android:text=" Create service-side "/> <button android:id=" @+id/but8 "android:layout_width=" Wrap_con Tent "android:layout_height=" Wrap_content "android:text=" connected to server Side "/> <button android:id=" @+id /but9 "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" Send "/&G T;</linearlayout></scrollview>



Manifest file

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.example.bluetoothtest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-s DK android:minsdkversion= "8" android:targetsdkversion= "/> <application android:allowback" Up= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@style /apptheme "> <activity android:name=" com.example.bluetoothtest.MainActivity "Android:la Bel= "@string/app_name" > <intent-filter> <action android:name= "android.intent.action . MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-filte r> </activity> </application><uses-permission android:name= "Android.permission.BLUETOOTH"/> <uses-permission Android:name= "AndroidOid.permission.BLUETOOTH_ADMIN "/></manifest> 




Note: Android phone A, Android phone B to install the software, and all click on the prompt to open (or automatically open), and then Android phone a click on the change visibility and Click Create Server, Android phone b Click to find the device, if the first device found for Android phone, b mobile click the link To the server, you can enter text in the text box after the prompt has been connected, and then click Send

Please install on the phone to use!


Engineering http://pan.baidu.com/s/1eQ3nc3o



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.