Android Studio phase 33rd-Bluetooth development First Knowledge ~

Source: Internet
Author: User

Meet the Pit daddy's teammates only accept the reality and solve the problem ~

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/8E/97/wKioL1jGXTPwT6wqAADi_mTTbrk301.png "title=" Qq20170313164907.png "width=" "height=" 366 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:600PX;HEIGHT:366PX; "alt = "Wkiol1jgxtpwt6wqaadi_mttbrk301.png"/>

Let's start by introducing almost all the methods you can find online:

1. First, to operate Bluetooth, first to add permissions in the Androidmanifest.xml

<uses-permissionandroid:name= "Android.permission.BLUETOOTH_ADMIN"/><uses-permissionandroid:name= " Android.permission.BLUETOOTH "/>

2. Under the Android.bluetooth package, these things can be used:

650) this.width=650; "src=" Https://s5.51cto.com/wyfs02/M02/8E/94/wKioL1jGN4mhMv5zAAB8ArDTg_M012.png "title=" u$} BXJ]{X61[5{M~QLR7 (87.png "alt=" Wkiol1jgn4mhmv5zaab8ardtg_m012.png "/>

3. We generally use the bluetoothadapter to achieve the basic requirements:

Canceldiscovery (): Cancel discovery, that is, call this method when we are searching for the device will not continue to search

Disable (): Turn off Bluetooth

Enable (): Turn on Bluetooth, this method to turn on Bluetooth will not pop up the prompt, more time we need to ask the user whether to open, the two lines of code is also open Bluetooth, but will prompt the user:

Turn on Bluetooth if (!mbluetoothadapter.isenabled ()) {Intent intent1 = new Intent (bluetoothadapter.action_request_enable);    Startactivityforresult (Intent1, Enable_blue); Do not prompt, force open//Madapter.enable ();} else {close_blue ();}

    

@Overrideprotected  void onactivityresult (int requestcode, int resultcode, intent  data)  {    // TODO Auto-generated method stub     super.onactivityresult (requestcode, resultcode, data);    if  ( Requestcode == enable_blue)  {        if  ( RESULTCODE&NBSP;==&NBSP;RESULT_OK)  {             toast.maketext (this,  "Bluetooth on Success",  toast.length_short). Show ();             open_blue ();         } else  if  (resultcode == result_canceled)  {             toast.maketext (this,  "bluetooth start Failed",  toast.length_short). Show ();        &nbsP;    close_blue ();        }     }}

GetAddress (): Get local Bluetooth address

Getdefaultadapter (): Gets the default Bluetoothadapter, in fact, there's only one way to get Bluetoothadapter

GetName (): Get the local bluetooth name

Getremotedevice (String address): Get a remote Bluetooth device based on the Bluetooth location

GetState (): Gets the current status of the local Bluetooth adapter (more needed when it feels possible to debug)

Isdiscovering (): Determines whether the device is currently being looked up, is returned true

IsEnabled (): Determines whether Bluetooth is turned on, turned on returns True, otherwise, returns false

Listenusingrfcommwithservicerecord (String name,uuid UUID): Based on the name, the UUID creates and returns Bluetoothserversocket, This is the first step in creating a Bluetoothsocket server side

StartDiscovery (): Start Search, this is the first step in search


4. Enable the device to be searched:

Start by judging the initial state:

The native device is scanned for initial state bufenif  (Mbluetoothadapter.getscanmode ()  == 23)  {    // Turn on the status setting bufen            //open Operation          //pop-up window//                     intent intent = new intent (//                              bluetoothadapter.action_request_discoverable);//                     // Time to set the Bluetooth visibility, the method itself specifies a maximum of 300 seconds to be visible//                     intent.putextra (bluetoothadapter.extra_discoverable_duration,  Blue_time);//                     Startactivityforresult (intent, search_blue);         //No window          settingblueutils.setdiscoverabletimeout (;   )      shezhi_blue_research (true);         new  handler (). postdelayed (New runnable ()  {              @Override             public  void run ()  {                 closediscoverabletimeout ();                 shezhi_blue_research (False);             }        }, 120* 1000);}  else if  (Mbluetoothadapter.getscanmode ()  == 21)  {    // Off state setting Bufen    closediscoverabletimeout ();}

Then set the code section:

Open:

Public static void setdiscoverabletimeout (int timeout)  {     Bluetoothadapter adapter = bluetoothadapter.getdefaultadapter ();     try  {        Method setDiscoverableTimeout =  BluetoothAdapter.class.getMethod ("Setdiscoverabletimeout",  int.class);         setdiscoverabletimeout.setaccessible (True);         Method setscanmode = bluetoothadapter.class.getmethod ("Setscanmode", int.class,  Int.class);         setscanmode.setaccessible (True);         setdiscoverabletimeout.invoke (adapter, timeout);         setscanmode.invoke (Adapter, bluetoothadapter.scan_mode_connectable_discoverable,  timeout);     } catch  (exception e)  {        e.printstacktrace ();     }}

     Close:

Public static void closediscoverabletimeout ()  {    bluetoothadapter  adapter = bluetoothadapter.getdefaultadapter ();    try {         Method setDiscoverableTimeout =  BluetoothAdapter.class.getMethod ("Setdiscoverabletimeout",  int.class);         setdiscoverabletimeout.setaccessible (True);         Method setscanmode = bluetoothadapter.class.getmethod ("Setscanmode", int.class,  Int.class);         setscanmode.setaccessible (True);         setdiscoverabletimeout.invoke (adapter, 1);         setscanmode.invoke (adapter, bluetoothadapter.scan_mode_connectable, 1);     } catch  (exception e)  {        e.printstacktrace ();     }} 


5. How to crawl the list of Bluetooth lists:

Get all Bluetooth devices that are already bound set<bluetoothdevice> devices = mbluetoothadapter.getbondeddevices (); list<bluetoothdevice> mList1 = new arraylist<> (); if (devices.size () > 0) {mList1 = new Arraylist<> ;(d evices);}


6. Register to search for Bluetooth receiver:

Intentfilter mfilter = new Intentfilter (bluetoothadapter.action_discovery_finished); Mfilter.addaction ( Bluetoothdevice.action_found); mfilter.addaction (bluetoothdevice.action_bond_state_changed); MFilter.addAction ( bluetootha2dp.action_connection_state_changed); mfilter.addaction (bluetootha2dp.action_playing_state_changed); Registerreceiver (Mreceiver, Mfilter);

Private broadcastreceiver mreceiver = new broadcastreceiver ()  {      @Override     public void onreceive (context context, intent  intent)  {        // TODO Auto-generated  method stub        string action =  Intent.getaction ();        //  get the Bluetooth device you've already found          if  (Action.equals (bluetoothdevice.action_found))  {             BluetoothDevice device11 = intent                      .getparcelableextra (Bluetoothdevice.extra_device);             //  found a Bluetooth device that is not already bound             if  (!is_shebei_open)  {                 receiver1 (DEVICE11);             } else {                 receiver11 (DEVICE11);             }             /** when the state of the binding changes */        } else  if  (Action.equals (bluetoothdevice.action_bond_state_changed))  {             bluetoothdevice device22 = intent.getparcelableextra ( Bluetoothdevice.extra_device);             Receiver2 (device22, mainactivity_Bluetooth.this);        } else if  (Action.equals ( bluetoothadapter.action_discovery_finished))  {             receiver3 ();        } else if  ( Action.equals (bluetootha2dp.action_connection_state_changed))  {             int state = intent.getintextra (BluetoothA2dp.EXTRA_STATE,  bluetootha2dp.state_disconnected);             Receiver4 (state);        } else if  (Action.equals ( bluetootha2dp.action_playing_state_changed))  {             int state = intent.getintextra (bluetootha2dp.extra_state,  bluetootha2dp.state_not_playing);            receiver5 (state);         }    }};


Finally, many connections have not been resolved, the individual tried a lot of methods, if you have a way to tell me, thank you ~

Address: https://github.com/geeklx/MyApplication/tree/master/p010_recycleviewall/src/main/java/com/example/p010_ Recycleviewall/bluetooth


650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M02/8E/97/wKiom1jGS97wy11TAAQ8zhtm9UY132.gif "title=" C2adb464tw1etn3dny1qng208c04p7bj.gif "alt=" Wkiom1jgs97wy11taaq8zhtm9uy132.gif "/>

This article is from the "Liangxiao Technology Center" blog, please be sure to keep this source http://liangxiao.blog.51cto.com/3626612/1905941

Android Studio phase 33rd-Bluetooth development First Knowledge ~

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.