Core code to write Bluetooth-related functions in Android development _android

Source: Internet
Author: User

A. What is blue tooth (Bluetooth)?
1.1 Buletooth is currently the most widely used wireless communication protocol
1.2 Mainly for short distance equipment communication (10m)
1.3 is commonly used to connect headphones, mouse and mobile communication equipment.
two. Bluetooth-related APIs
2.1 Bluetoothadapter:
Represents a local Bluetooth adapter
2.2 Bluetoothdevice
Represents a remote Bluetooth device
three. Scan already paired Bluetooth devices (1)
Note: Must be deployed on the real phone, the simulator can not be implemented
First you need to declare Bluetooth permissions in Androidmanifest.xml
<user-permission android:name= "Android.permission.BLUETOOTH"/>
Pairing Bluetooth requires manual operation:
1. Open Settings--> wireless network--> bluetooth Check Open
2. Turn on Bluetooth settings to scan the surrounding Bluetooth device (which can be paired with your laptop) and click to match
Pop-up prompts on your computer: adding devices
Displays the pairing code between the calculation and the device, requiring confirmation of pairing
Similar prompts will be displayed on the phone.
four. Scan already paired Bluetooth devices (2)
4.1 Getting Bluetoothadapter objects
4.2 Determine if the current mobile device has Bluetooth
4.3 Determine if Bluetooth is turned on on the current mobile device
4.4 Get all Bluetooth device objects that have been paired


The core code for Bluetooth pairing implementation is as follows:

Mainactivity:import Java.util.Iterator; 
 
Import Java.util.Set; 
Import android.app.Activity; 
Import Android.bluetooth.BluetoothAdapter; 
Import Android.bluetooth.BluetoothDevice; 
Import android.content.Intent; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
 
Import Android.widget.Button; 
  public class Mainactivity extends activity {Private Button button = null; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.main); 
    Button = (button) Findviewbyid (R.id.buttonid); Button.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//Get Blue 
        Toothadapter object, which is the bluetoothadapter adapter = Bluetoothadapter.getdefaultadapter () that the Android 2.0 begins to support; Adapter is not equal to NULL, indicating that the machine has a Bluetooth device if (adapter!= null) {System. OUT.PRINTLN ("This machine has Bluetooth equipment!") 
          "); If the Bluetooth device does not open if (!adapter.isenabled ()) {Intent Intent = new Intent (bluetoothadapter.action_request_e 
            nable); 
          Request to open Bluetooth device startactivity (intent); 
          //Get the set of paired remote Bluetooth devices set<bluetoothdevice> devices = adapter.getbondeddevices (); 
              if (Devices.size () >0) {for (iterator<bluetoothdevice> it = Devices.iterator (); It.hasnext ();) { 
              Bluetoothdevice device = (bluetoothdevice) it.next (); 
            Print out the physical address of the remote Bluetooth device System.out.println (device.getaddress ()); }else{System.out.println ("There are no paired remote Bluetooth devices!") 
          "); }else{System.out.println ("No Bluetooth device on this machine!") 
        "); 
  } 
      } 
    }); 

 } 
}


Modify the visibility of the native Bluetooth device and scan the available Bluetooth devices around it
1. To modify the visibility of a native Bluetooth device
2. Scan the available Bluetooth devices around

Eg:
I. Manifest document Adroidmanifest.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= 
"http://schemas.android.com/apk/res/" Android " 
   package=" Com.se7en " 
   android:versioncode=" 1 " 
   android:versionname=" 1.0 "> 
  < USES-SDK android:minsdkversion= "8"/> 
 
  <application android:icon= "@drawable/icon" android:label= "@string App_name "> 
    <activity android:name=". Mainactivity " 
         android:label=" @string/app_name "> 
      <intent-filter> 
        <action android:name=" Android.intent.action.MAIN "/> 
        <category android:name=" Android.intent.category.LAUNCHER "/>" 
      </intent-filter> 
    </activity> 
  </application> 
  <uses-permission android:name= " Android.permission.BLUETOOTH "/> 
   
  <!-If you need to manage Bluetooth devices, such as modifying visibility, you need the following permissions-> 
  <uses-permission android: Name= "Android.permission.BLUETOOTH_ADMIN"/> 
</manifest> 

Two. layout file: Main.xml:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:orientation=" vertical " 
  android:layout_width=" fill_parent " 
  android:layout_" height= "Fill_parent" 
  > 
  <textview  
    android:layout_width= "fill_parent"  
    android:layout_ height= "Wrap_content"  
    android:text= "@string/hello"/> <button android:id=  
    "@+id/ Discoverbutton " 
    android:layout_width=" fill_parent " 
    android:layout_height=" Wrap_content " 
    Android : text= "Set visibility"/> 
  <button  
    android:id= " 
    @+id/scanbutton" android:layout_width= "Fill_parent" 
    android:layout_height= "wrap_content" 
    android:text= "start scanning"/> 
</LinearLayout> 

Three. Mainactivity:

Import android.app.Activity; 
Import Android.bluetooth.BluetoothAdapter; 
Import Android.bluetooth.BluetoothDevice; 
Import Android.content.BroadcastReceiver; 
Import Android.content.Context; 
Import android.content.Intent; 
Import Android.content.IntentFilter; 
Import Android.os.Bundle; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
 
Import Android.widget.Button; 
  public class Mainactivity extends activity {private Button Discoverbutton = null; 
  Private Button Scanbutton = null; 
  Private Bluetoothadapter adapter = null; 
  Private Bluetoothreceiver bluetoothreceiver = null; /** called the activity is a. 
    * * @Override public void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
     
    Setcontentview (R.layout.main); 
     
    adapter = Bluetoothadapter.getdefaultadapter (); 
    Discoverbutton = (Button) Findviewbyid (R.id.discoverbutton); 
Scanbutton = (Button) Findviewbyid (R.id.scanbutton);    Modify the visibility of the Bluetooth device Discoverbutton.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View view) 
 
{Intent discoverintent = new Intent (bluetoothadapter.action_request_discoverable); Set Bluetooth visibility, 500 indicates the visible time (in seconds), and the default is Discoverintent.putextra (Bluetoothadapter.extra_discoverable_duration when the value is greater than 300). 
500); 
      StartActivity (discoverintent); 
     
    } 
    }); Scanbutton.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//start scanning around Bluetooth 
      Device, which is invoked asynchronously and returned with a broadcast mechanism, so you need to create a broadcastreceiver to get the information adapter.startdiscovery (); 
     
    } 
    }); 
    Set broadcast received filter Intentfilter Intentfilter = new Intentfilter (bluetoothdevice.action_found); 
    Receiver Bluetoothreceiver = new Bluetoothreceiver () for creating Bluetooth broadcast information; 
       
  Registered broadcast receiver Registerreceiver (bluetoothreceiver,intentfilter); Private class Bluetoothreceiver extends broadcastreceiver{@Override public void onReceive (context, Intent Intent) {//Get scanned remote Bluetooth device Bluetoothdevice device = Intent.getparcelableextra ( 
      Bluetoothdevice.extra_device); 
    System.out.println (Device.getaddress ()); 
 } 
     
  } 
}

Related Article

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.