This article is mainly about the Android Bluetooth device open and close, very simple, see the code for details.
1.mainactivity.java
public class Mainactivity extends Activity {private String tag= "mainactivity";p rivate button startbtn;private button stop Btn; Bluetoothadapter Mbluetoothadapter; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Startbtn= (Button) Findviewbyid (R.ID.START_BTN); Stopbtn= (Button) Findviewbyid (R.ID.STOP_BTN); Mbluetoothadapter = Bluetoothadapter.getdefaultadapter (); if (Mbluetoothadapter = = null) {Toast.maketext (this, "the computer does not find Bluetooth hardware or drivers!) ", Toast.length_short). Show (); Finish (); } startbtn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-g enerated method Stub//If local Bluetooth is not turned on, turn on if (!mbluetoothadapter.isenabled ()) {mbluetoothadapter.enable () ; Toast.maketext (Getapplicationcontext (), "Bluetooth is turned on", Toast.length_short). Show (); } }}); Stopbtn.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//TODO auto-generated method Stub if (mbluetoothadapter.isenabled ()) {mbluetoothadapter.disable ();//Turn off Bluetooth toast.maketext (Getapplicationcontext () , "Bluetooth is Off", Toast.length_short). Show (); }} }); } }
2. layout file Activity_main.xml
<linearlayout 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 " android:orientation= "vertical" > <textview android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:textstyle= "bold" android:textsize= "24dip" android: layout_gravity= "center" android:text= "Bluetooth open and close test"/> <button android:id= "@+id/start_btn" Android: Layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "open"/> <Button android:id = "@+id/stop_btn" android:layout_width= "fill_parent" android:layout_height= "wrap_content" android:text= "Off"/> </LinearLayout>
3. Configure file Androidmanifest.xml Add permissions
<uses-permission android:name= "Android.permission.BLUETOOTH"/> <uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Bluetooth device's turn on and off function implementation