Bluetooth active pairing for mobile phone connection in android Development

Source: Internet
Author: User

The previous article introduced three methods of phone pairing connection. This article describes how to search for Bluetooth devices and actively pair and connect to them using a complete code example.

Package jason.com; import java. io. IOException; import java. lang. reflect. method; import java. util. arrayList; import java. util. list; import java. util. UUID; import android. app. activity; import android. bluetooth. export thadapter; import android. bluetooth. export thdevice; import android. bluetooth. export thsocket; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; import android. content. intentFilter; import android. OS. bundle; import android. util. log; import android. view. view; import android. widget. adapterView; import android. widget. arrayAdapter; import android. widget. button; import android. widget. listView; import android. widget. toast; import android. widget. toggleButton; public class extends thtestactivity extends Activity {// This UUID indicates the serial port service static final String SPP_UUID = "Courier"; Button btnSearch, btnDis, btnExit; ToggleButton tbtnSwitch; ListView lvBTDevices; ArrayAdapter
 
  
AdtDevices; List
  
   
LstDevices = new ArrayList
   
    
(); Fig; public static fig; @ Overridepublic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); // Button set btnSearch = (Button) this. findViewById (R. id. btnSearch); btnSearch. setOnClickListener (new ClickEvent (); btnExit = (Button) this. findViewById (R. id. btnExit); btnExit. setOnClickListener (new ClickEvent (); btnDis = (Button) this. findViewById (R. id. btnDis); btnDis. setOnClickListener (new ClickEvent (); // ToogleButton sets tbtnSwitch = (ToggleButton) this. findViewById (R. id. tbtnSwitch); tbtnSwitch. setOnClickListener (new ClickEvent (); // ListView and its data source adapter lvBTDevices = (ListView) this. findViewById (R. id. lvDevices); adtDevices = new ArrayAdapter
    
     
(This, android. r. layout. simple_list_item_1, lstDevices); lvBTDevices. setAdapter (adtDevices); lvBTDevices. setOnItemClickListener (new ItemClickEvent (); btAdapt = descrithadapter. getdefaadapter adapter (); // initialize the local Bluetooth function // ====================================== ========================================/// modified by jason0539 search for jason0539 to enter my blog/** if (btAdapt. getState () = descrithadapter. STATE_OFF) // read the Bluetooth status and display * tbtnSwitch. setChecked (false); else if (btAdapt. getState () = * initialize thadapter. STATE_ON) tbtnSwitch. setChecked (true); */if (btAdapt. isEnabled () {tbtnSwitch. setChecked (false);} else {tbtnSwitch. setChecked (true );} // ================================================ ======================================/// register a Receiver to obtain the result of the bluetooth device IntentFilter intent = new IntentFilter (); intent. addAction (descrithdevice. ACTION_FOUND); // use BroadcastReceiver to obtain the search result intent. addAction (descrithdevice. ACTION_BOND_STATE_CHANGED); intent. addAction (descrithadapter. ACTION_SCAN_MODE_CHANGED); intent. addAction (descrithadapter. ACTION_STATE_CHANGED); registerReceiver (searchDevices, intent);} private BroadcastReceiver searchDevices = new BroadcastReceiver () {public void onReceive (Context context, Intent intent) {String action = intent. getAction (); Bundle B = intent. getExtras (); Object [] lstName = B. keySet (). toArray (); // display all received messages and their details for (int I = 0; I <lstName. length; I ++) {String keyName = lstName [I]. toString (); Log. e (keyName, String. valueOf (B. get (keyName);} retrieve thdevice device = null; // retrieve the device's MAC address if (retrieve thdevice. ACTION_FOUND.equals (action) {device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); if (device. getBondState () = descrithdevice. BOND_NONE) {String str = "unpaired |" + device. getName () + "|" + device. getAddress (); if (lstDevices. indexOf (str) =-1) // prevents repeated addition of lstDevices. add (str); // obtain the device name and mac address adtDevices. notifyDataSetChanged () ;}} else if (descrithdevice. ACTION_BOND_STATE_CHANGED.equals (action) {device = intent. getParcelableExtra (effecthdevice. EXTRA_DEVICE); switch (device. getBondState () {case when thdevice. BOND_BONDING: Log. d ("maid", "pairing ...... "); break; case when thdevice. BOND_BONDED: Log. d ("complete thtestactivity", "complete pairing"); connect (device); // connect to the device break; case when thdevice. BOND_NONE: Log. d ("cancthtestactivity", "unpairing"); default: break ;}}};@ Overrideprotected void onDestroy () {this. unregisterReceiver (searchDevices); super. onDestroy (); android. OS. process. killProcess (android. OS. process. myPid ();} class ItemClickEvent implements AdapterView. onItemClickListener {@ Overridepublic void onItemClick (AdapterView
     Arg0, View arg1, int arg2, long arg3) {if (btAdapt. isDiscovering () btAdapt. cancelDiscovery (); String str = lstDevices. get (arg2); String [] values = str. split ("\\|"); String address = values [2]; Log. e ("address", values [2]); then thdevice btDev = btAdapt. getRemoteDevice (address); try {Boolean returnValue = false; if (btDev. getBondState () = descrithdevice. BOND_NONE) {// call thinthdevice using the reflection method. createBond (Blu Descrithdevice remoteDevice); Method createBondMethod = descrithdevice. class. getMethod ("createBond"); Log. d ("Maid activity", "start pairing"); returnValue = (Boolean) createBondMethod. invoke (btDev);} else if (btDev. getBondState () = descrithdevice. BOND_BONDED) {connect (btDev) ;}} catch (Exception e) {e. printStackTrace () ;}} private void connect (effecthdevice btDev) {UUID uuid = UUID. fromString (SPP_UUID ); Try {btSocket = btDev. createRfcommSocketToServiceRecord (uuid); Log. d ("thtestactivity", "Start to connect... "); btSocket. connect ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} class ClickEvent implements View. onClickListener {@ Overridepublic void onClick (View v) {if (v = btnSearch) // search for a bluetooth device and display the result in BroadcastReceiver {if (btAdapt. getState () = descrithadapter. STATE_OFF ){/ /If Toast is not enabled for Bluetooth. makeText (effecthtestactivity. this, "Please turn on Bluetooth first", 1000 ). show (); return;} if (btAdapt. isDiscovering () btAdapt. cancelDiscovery (); lstDevices. clear (); Object [] lstDevice = btAdapt. getBondedDevices (). toArray (); for (int I = 0; I <lstDevice. length; I ++) {effecthdevice device = (effecthdevice) lstDevice [I]; String str = "paired |" + device. getName () + "|" + device. getAddress (); lstDevices. add (str); // Obtain the device name and mac address adtDevices. notifyDataSetChanged ();} setTitle ("local Bluetooth address:" + btAdapt. getAddress (); btAdapt. startDiscovery ();} else if (v = tbtnSwitch) {// start/Close the local Bluetooth if (tbtnSwitch. isChecked () = false) btAdapt. enable (); else if (tbtnSwitch. isChecked () = true) btAdapt. disable ();} else if (v = btnDis) // the local machine can be searched for {Intent discoverableIntent = new Intent (effecthadapter. ACTION_REQUEST_DISCOVERABLE); discovera BleIntent. putExtra (effecthadapter. EXTRA_DISCOVERABLE_DURATION, 300); startActivity (discoverableIntent);} else if (v = btnExit) {try {if (btSocket! = Null) btSocket. close () ;}catch (IOException e) {e. printStackTrace () ;}%thtestactivity. this. finish ();}}}}
    
   
  
 


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.