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 () , "Wait for the user to connect.。
。 ", 1). Show ();} if (msg.what==-2) {toast.maketext (), "Getapplicationcontext ()," is connected to the 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, now only can use the default Bluetooth adapter, through this method can get to the default adapter Bluetooth=bluetoothadapter.getdefaultadapter ();//Enable andDisabling Bluetoothadapter is a time-consuming asynchronous operation that requires a register of receiver monitoring status 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 device scanning. Register the receiver is able to receive the scanned device//through (Bluetoothdevice) Intent.getparcelableextra (bluetoothdevice.extra_device)// Able to 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//Can be directly using the Enable () method to startBluetooth Friendly name But2.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View arg0) { Bluetooth.enable ();}}); /Use the following statement to be able to pop up the dialog prompt whether open, Onactivityresult () method to get user options 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 ();}); /change 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 the service 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 ();//Plug-in method. Thread Handler.sendemptymessage ( -2), Outputstream=serversocket.getoutputstream (), new thread () {///When new connection is required. Leave 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 changed" + 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 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) {}}}}
Layout files such as the following
<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= "self-initiated"/> <button an Droid:id= "@+id/but3" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android : text= "prompt to open"/> <button android:id= "@+id/but4" android:layout_width= "Wrap_content" android:l ayout_height= "Wrap_content" android:text= "Get Info"/> <button android:id= "@+id/but5" Android:la Yout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Change visibility"/> <Button Android:id= "@+id/but6" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" an droid:text= "Find Device"/> <button android:id= "@+id/but7" android:layout_width= "wrap_content" android:layout_height= "Wrap_ Content "android:text=" Create service-side "/> <button android:id=" @+id/but8 "android:layout_width=" Wrap_c Ontent "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 "/ ></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>
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwluz2nodw53zwlsawfuzw==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/southeast ">
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwluz2nodw53zwlsawfuzw==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/southeast ">
watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvcwluz2nodw53zwlsawfuzw==/font/5a6l5l2t/fontsize/400/fill/ I0jbqkfcma==/dissolve/70/gravity/southeast ">
Note: Android phone A, Android phone B to install the software, and all click on the prompt to open (or self-open), then Android phone a click change visibility and Click Create Server, Android phone b click Find Device. If you find the first device for Android phone A, B mobile click on the link to the server. After the prompt is connected, you can enter text in the text box and click Send
Please install on the phone to use!
Project Http://pan.baidu.com/s/1eQ3nc3o
Andoran Tooth communication