Android: Bluetooth 4.0-ble-Summary =1.0

Source: Internet
Author: User

Requirements: BLE connection and communication (do now-device on-search device-connect device)Resources: Some demos and official documents from the Web

:


1-ble is a Android4.3 version of the api-to provide some conceptual things or it is necessary to understand
At present, the Android real machine can only accept and control products-that is, the client side of the-server end is only a product-and Apple seems to be a mobile phone can be used as the receiving end can also be sent-
The basic concept is central and peripheral--the handset as the center--the product as the periphery--and both are connected by ble--
So I understand that the--gatt protocol for messaging is based on ATT--they contain a set of information that is server--there can be a lot of characti in the server ... And every feature is the constant information we need.
If there is something wrong with understanding it can be pointed out-after all, my understanding and cognition of this piece is only a few days-

2-Let's go to the formal lecture section below
App permissions Issue = = Call the Bluetooth device to claim permission = =

<span style= "FONT-SIZE:14PX;" ><uses-permission android:name= "Android.permission.BLUETOOTH"/><uses-permission android:name= " Android.permission.BLUETOOTH_ADMIN "/></span>

= = Sometimes the implementation of the various parts of our app is based on Bluetooth then we need to explain that the device is bluetooth only applicable = =

<span style= "FONT-SIZE:14PX;" ><uses-feature        android:name= "Android.hardware.bluetooth_le"        android:required= "true"/></ Span>

3-Building a new project-testbluetooth

Put out Mainactivity.java code.

Package Com.example.testbluetooth;import Java.util.arraylist;import Android.app.activity;import Android.app.listactivity;import Android.bluetooth.bluetoothadapter;import Android.bluetooth.bluetoothadapter.lescancallback;import Android.bluetooth.bluetoothdevice;import Android.bluetooth.bluetoothmanager;import Android.content.context;import Android.content.intent;import Android.content.pm.packagemanager;import Android.os.bundle;import Android.os.handler;import Android.util.Log; Import Android.view.layoutinflater;import android.view.menu;import android.view.menuitem;import Android.view.View; Import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.listview;import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends Listactivity {private final static String TAG = "Bluetoohth_test";p rivate ledevicelistadapter mledevicelistadapter;private bluetoothadapter Mbluetoothadapter;private Boolean mscanning;private Handler mhandler;private static Final int request_enable_bt = 1;//Stops scanning after seconds.private static final long scan_period = 10000; @Ov errideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Getactionbar (). Settitle (r.string.title_devices); mhandler = new Handler ();//Determine if BLELOG.I (TAG, "wheter_support_ble") is supported; Getpackagemanager (). Hassystemfeature (Packagemanager.feature_bluetooth_le)) {Toast.maketext (this, R.string.ble_ not_supported, Toast.length_short). Show (); Finish ();} LOG.I (TAG, "Get_about_ble_api"); final Bluetoothmanager Bluetoothmanager = (bluetoothmanager) Getsystemservi        CE (context.bluetooth_service);                Mbluetoothadapter = Bluetoothmanager.getadapter (); if (Mbluetoothadapter = = null) {Toast.maketext (this, r.string.error_bluetooth_not_supported, Toast.length_shor            T). Show ();            Finish ();        Return }} @Overrideprotected void Onresume () {super.onresume ()/////For Bluetooth connection//ensures Bluetooth is EnabLED on the device. If Bluetooth is notlog.i (TAG, "connect_ble"); if (!mbluetoothadapter.isenabled ()) {if (!mbluetoothadapter.isenabled ()) {Intent enablebtintent = new Intent (bluetoothadapter.action_request_enable); Startactivityforresult (Enablebtintent, REQUEST_ENABLE_BT);}} Initializes list view Adapter.mledevicelistadapter = new Ledevicelistadapter (); Setlistadapter (Mledevicelistadapter ); Scanledevice (true);} /** * Real-time search for Bluetooth devices * devices are scanned every once and the device gets a prompt refresh-via Notifydatasetchange method * @author Admin * */private class Ledevicelistadap ter extends Baseadapter {private arraylist<bluetoothdevice> mledevices;private layoutinflater mInflator;public Ledevicelistadapter () {super (); mledevices = new arraylist<bluetoothdevice> (); minflator = MainActivity.this.getLayoutInflater ();} Add a device into the list of public void AddDevice (Bluetoothdevice device) {if (!mledevices.contains (device)) {Mledevices.add (device);}} Gets the corresponding device public bluetoothdevice getdevice (int position) {return mledevices.get (position) in the subkey;} Empty columnsTable Data public void Clear () {mledevices.clear ();} @Overridepublic int GetCount () {return mledevices.size ();} @Overridepublic Object getItem (int i) {return mledevices.get (i);} @Overridepublic long Getitemid (int i) {return i;} @Overridepublic View GetView (int i, view view, ViewGroup viewgroup) {Viewholder viewholder;//general ListView Optimizatio N code.if (view = null) {view = Minflator.inflate (R.layout.listitem_device, null); Viewholder = new Viewholder (); viewhold Er.deviceaddress = (TextView) View.findviewbyid (r.id.device_address); viewholder.devicename = (TextView) View.findviewbyid (R.id.device_name); View.settag (Viewholder);} else {Viewholder = (Viewholder) View.gettag ();} The corresponding devices are processed bluetoothdevice device = Mledevices.get (i); final String devicename = Device.getname (); if (devicename! = null & amp;& devicename.length () > 0) viewHolder.deviceName.setText (devicename); ElseviewHolder.deviceName.setText ( R.string.unknown_device); ViewHolder.deviceAddress.setText (Device.getaddress ()); return view;}}Static class Viewholder {TextView devicename; TextView deviceaddress;} /** * Scan device * @param enable */private void Scanledevice (Final Boolean enable) {if (enable) {//Stops SC            Anning after a pre-defined scan period. Mhandler.postdelayed (New Runnable () {@Override public void run () {MScan                    ning = false;                    Mbluetoothadapter.stoplescan (Mlescancallback);                Invalidateoptionsmenu ();            }}, Scan_period);            Mscanning = true;        Mbluetoothadapter.startlescan (Mlescancallback);            } else {mscanning = false;        Mbluetoothadapter.stoplescan (Mlescancallback); } invalidateoptionsmenu ()///Update the menu bar information}//Scan to the Bluetooth device response settings Private Bluetoothadapter.lescancallback Mlescancallbac K = new Bluetoothadapter.lescancallback () {@Override public void Onlescan (final bluetoothdevice device, int rssi, byte[] Scanrecord) {Runonuithread (new Runnable () {@Override public void run () {                    Mledevicelistadapter.adddevice (device);                Mledevicelistadapter.notifydatasetchanged ();        }            });         }    };        @Override protected void OnPause () {super.onpause ();        Scanledevice (FALSE);    Mledevicelistadapter.clear (); }//the option to scan and pause @Override public boolean oncreateoptionsmenu (Menu menu) {getmenuinflater (). Inflate (r.menu.ma        in, menu);            if (!mscanning) {Menu.finditem (r.id.menu_stop). setvisible (false);            Menu.finditem (R.id.menu_scan). setvisible (True);        Menu.finditem (R.id.menu_refresh). Setactionview (NULL);            } else {Menu.finditem (r.id.menu_stop). setvisible (True);            Menu.finditem (R.id.menu_scan). setvisible (false); Menu.finditem (R.id.menu_refresh). Setactionview (R.layout.actionbar_indeterminate_progress);    } return true;            }//Click event @Override Public boolean onoptionsitemselected (MenuItem item) {switch (Item.getitemid ()) {                Case R.id.menu_scan:mledevicelistadapter.clear ();                Scanledevice (TRUE);            Break                Case R.id.menu_stop:scanledevice (FALSE);        Break    } return true; }/* Listen for events for each subkey * @see Android.app.listactivity#onlistitemclick (Android.widget.ListView, Android.view.Vie W, int, long) */@Override protected void Onlistitemclick (ListView l, View v, int position, long id) {fi        NAL Bluetoothdevice device = mledevicelistadapter.getdevice (position);        if (device = = null) return;        Final Intent Intent = new Intent (this, devicecontrolactivity.class);        Intent.putextra (Devicecontrolactivity.extras_device_name, Device.getname ()); Intent.putextra (Devicecontrolactivity.extras_devIce_address, Device.getaddress ());            if (mscanning) {Mbluetoothadapter.stoplescan (mlescancallback);        Mscanning = false;    } startactivity (Intent);  } @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {//User chose        Not to enable Bluetooth.            if (Requestcode = = Request_enable_bt && ResultCode = = activity.result_canceled) {finish ();        Return    } super.onactivityresult (Requestcode, ResultCode, data); }}


3.1-Post---Listitem_device.xml
</pre><pre name= "code" class= "java" ><pre name= "code" class= "HTML" ><?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"              android:orientation = "vertical"              android:layout_width= "match_parent"              android:layout_height= "wrap_content" >    < TextView android:id= "@+id/device_name"            android:layout_width= "match_parent" android:layout_height= "Wrap_            Content "            android:textsize=" 24DP "/>    <textview android:id=" @+id/device_address "            android:layout_ Width= "Match_parent"            android:layout_height= "wrap_content"            android:textsize= "12DP"/></ Linearlayout>


Not to be continued



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.