Android Wi_Fi编程

Android Wi_Fi编程 wi-Fi又称802.11b标准 在android.net.wifi包中提供了一些类管理设备的WiFi功能,主要包括ScanResult、WiFiConfiguration、WiFiInfo和wifiManager 1.ScanResult类 主要通过WiFi硬件的扫描来获取一些周边的WiFi热点的信息。(该类包括5个域) (1)BSSID 接入点的地址。 (2)SSID 网络的名字。 (3)capabilities 网络性能,包括接入点支持的认证、密钥管理、加密机制。 (4)frequency 以Mhz为单位的接入频率 (5)level 以dBm为单位的信号强度 2.wifiConfiguration类 WiFi的网络配置,包括安全配置等。包括6个子类 (1)WifiConfiguration.AuthAlgorthm 获取IEEE802.11的加密方法 (2)Wificonfiguration.GroupCipher 获取组密钥 (3)wificonfiguration.KeyMgmt 获得密码管理体制 (4)WiFiConfiguration.PairwiseCipher 获取WPA方式的成对密钥 (5)WiFiConfiguration.Protocol 获取加密协议 (6)WiFiConfiguration.Status获取当前网络状态 3.WifiInfo类 通过该类可以获得已经建立的或者处于活动状态的WiFi网络的状态信息。 4.WifiManger类 管理WiFi连接,其中定义了26个常量和23个方法。WifiManagerLock的作用为:在普通的状态下,如果WiFi的状态处于闲置,那么网络将会暂时中断,但是如果把当前的网络状态锁上,那么WiFi连通将会保持在一定状态,在结束锁定之后,才会恢复常态。 WiFi直连API WifiPpManager类提供了很多方法允许用户通过设备的WiFi模块来进行交互。 NFC API简介 android对NFC的支持主要在android.nfc包中。包括类NFcAdapter、NdefMessage 1.NFCAdapter代表设备上的NFC硬件。 2.NdefMessage代表一个NDEF数据信息,NDEF(NFC Data Exchange Format)是设备与标签传输数据的标准格式。 android NFC基本工作流程如下: 步骤1:通过android.nfc.NfcAdapter.getDefaultAdapter()取得手机的objNfcAdapter 步骤2:通过objNfcAdapter.isEnabled()查询手机是否支持NFC 步骤3:如果手机支持NFC,手机内置的NFC扫描器(相当于NFCAdapter)扫描到电子标签后,就会想程序发送ACTION_TAG_DISCOVERED的Intent,Intent的extras机构中会包含NDEF。 步骤4:如果接收到ACTION_TAG_DISCOVERED,就提取NdefMessage,并在此基础上进行提取NdefRecord 在使用NFC API的时候,应用必须在AndroidMinifest.xml中声明获取使用权限最新SDK为10 申请市场过滤 转载注明: http://www.etongwl.com/?p=645

2015年2月11日 · 1 分钟 · 天边的星星

Android USB编程基础知识

USB编程 USB编程分为USB HOST(主机模式)和USB Accessory(配件模式) USB相关操作的类都集中在android.hardware.usb命名空间中 1.USB Accessory API简介 配件模式中两个重要的类:UsbAccessory和UsbMnanger,其中通过UsbManager可以获得USB状态信息,并负责和USB配件进行通信;UsbAccessory代表一个USB配件并且包含获取配件特定信息的方法。 定义UsbManager对话和UsbAccessory对象的方法. 通过Context.USB_SERVICE可以实例化UsbManager对象 UsbManager manager=(UsbManager)getSystemService(Context.USB_SERVICE); 通过以下方式获取UsbAccessory对象 UsbAccessory accessory=(UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); 2.Android manifest文件配置 因为不是所有的设备都支持USB accessory API需要在manifest中使用元素声明应用支持它,值为:android.hardware.usb.accessory.支持的最小的api是API Level 12。 如果希望应用在USB配件连接时能够接收通知,则在主Activity中需要为android.hardware.usb.action.USB_ACCESSORY_ATTACHED这个Intent中指定一对和。 元素指向里一个xml资源文件,该文件包含希望得到的配件的一些特定信息。 这个XML资源文件中为希望过滤的配件声明元素。每一个都可以包含“制造商”、“模式”和“版本”这3个属性。资源文件要保存在res/xml/目录下,资源文件的名称必须和在元素中指定的名称相同。 例如: android manifest文件 <manifest ….> … <activity …> … res/xml/有个xml文件accessory_filter.xml <?xml version=”1.0″ encoding=”utf-8″?> 配件使用 1.通过一个可以过滤配件附加事件的意图过滤器来找到合适的连接配件,或者枚举所有已连接的配件来找到合适的某个配件 2.尚未获得许可的用户在与配件通信前需要获得权限 3.通过合适的端口与配件进行读写通信 用户可以通过两种方式发现配件:一种是使用Intent过滤器在用户连接配件时对其进行通知,另一种通过枚举已经连接的所有配件。 意图过滤使用android.hardware.usb.action.USB_ACCESSORY_ATTACHED指定一个意图进行过滤。在这个意图过滤中需要指定一个资源文件来特别说明这个usb配件的属性,例如制造商、模式和版本,当连接的配件和意图过滤条件匹配时,应用会收到一个通知。 在Activity中可以通过以下方式获得UsbAccessory,它代表了所有连接的配件 UsbAccessory accessory=(UsbAccessroy) intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY); 枚举所有支持的配件 当应用在运行的时候,可以在应用中枚举所有能够识别的配件。通过getAccessoryList()方法获得一个包含所有已连接USB配件的数组 UsbManager manager=(UsbManager) getSystemService(Content.USB_SERVICE); UsbAccessory[] accessoryList=mamager.getAccessoryList(); 注意:目前一次只能连接一个USB配件,但是这个API设计的在未来可用于支持多个配件 ...

2015年2月11日 · 1 分钟 · 天边的星星

Android Email编程

Android Email编程 1.android自带邮件系统 //创建Intent Intent intent=new Intent(); //设置对象动作 intent.setAction(Intent.ACTION_SEND); //设置对方邮件地址 intent.putExtra(Intent.ExTRA_EMAIL,new String[]{‘abc@163.com’,’a@gmail.com’}); //设置标题内容 intent.putExtra(Intent.EXTRA_SUBJECT,”test”); //设置邮件文本内容 intent.putExtra(Intent.EXTRA_TEXT,”text_mail”); //启动一个新的Activity,‘sending mail…’是在启动这个activity的等待时间时所显示的文字 startActivity(Intent.creatChooser(intent,”sending mail…”)); 2.android JavaMail设计 android中使用javamail需要依赖3个包:activation.jar,additionnal.jar,mail.jar 对于实现邮件的发送,还需要确保发送方能连接到发送方邮件服务器,一般邮件服务器都需要认证,只有通过认证才能连接,从而将邮件发出去。 以126为例: //创建一个身份验证,即定义Authenticator的子类,并重载getPasswordAuthentication()方法 class PuoupAuthenticatior extends Authenticator{ public PasswordAuthenication getPasswordAuthentication(){ String username=”from”;//邮箱登陆账号 String pwd=””;//登录密码 //返回PasswrodAuthentication对象 return new PasswordAuthentication(username,pwd); } } //实例化实现对象Properties Properties props=new Properties(); //设置smtp的服务器地址是:smtp.126.com props.put(“mail.smtp.host”,”smtp.126.com”); props.put(“mail.smtp.auth”,”true”);//设置smtp服务器身份验证 PopupAuthenticator auth=new PopupAuthenticator();//创建身份验证的实例 //创建会话(Session),用它管理连接 Session session=Session.getInstance(props,auth); //实例化MimeMessage对象 MimeMessage message=new MimeMessage(session); //设置发送方邮件地址 Address addressFrom=new InternetAddress(“a@126.com”,”FROM”); //设置收件人邮件地址 Address addressTo=new InternetAddress(“b@126.com”,”TO”); //收件人地址 Address addressCopy=new InternetAddress(“abc@gmail.com”,”abc”); //创建邮件内容 message.setContent(“hello”,”text/plain”); //或者使用message.setText(“Hello”); message.setSubject(“Title”); message.setFrom(addressFrom); message.setRecipient(Message.RecipientType.TO,addressTO); message.setRecipient(Message.RecipientType.CC,addressCopy); message.saveChanges(); //发送邮件 Transport transport=session.getTransport(“smtp”);//创建连接 transport.connect(“smtp.126.com”,”from”,”123456″); transport.send(message);//发送信息 transport.close();关闭连接 ...

2015年2月11日 · 1 分钟 · 天边的星星

Androi 加密和解密

Androi 加密和解密 1.DES加密和解密 import javax.crypto.Cipher; import javax.crypto.spec.iVparameterSpec; import javax.crypto.spec.SecretKeySpec; public class DES{ //初始化向量,随便填充 private static byte[] iv={1,2,3,4,5,6,7,8}; //DES 加密 encryptString为原文 encryptKey为秘钥 public static String encryptDes(String encryptString,String encryptKey) throws Exception{ //实例化IvParameterSpec对象,使用指定的初始化向量 IvParameterSpec zeroIV=newIvParameterSpec(iv); //实例化SecretKeySpec类,根据字节数组来构造SecretKey SecretKeySpec key=nnew SecretKeySpec(encryptKey.getBytes(),’DES’); //创建密码器 Cipher cipher=Cipher.getInstance(“DES/CBC/PKCE5Padding”); //用秘钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE,key,zeroIv); //执行加密操作 byte[] encryptedData=cipher.doFinal(encryptString.getBytes()); //返回加密后的数据 return Base64.encode(encryptedData); } //DES解密 decryptString为密文 decryptKey为密钥 pubbic static String decryptDes(String decryptString ,String decryptKey) throws Exception{ //先使用Base64解密 byte[] byteMi=new Base64().decode(decryptString); //实例化IvParamterSpec对象,使用指定的初始化向量 IvparameterSpec zeroIv=newIvParameterSpec(iv); //初始化SecretKeySpec类,根据字节数组来构造 SecretKeySpec key=new SecretKeySpec(decryptKey.getBytes(),”DES”); //创建密码器 Clipher cipher=Cipher.getInstance(“DES/CBC/PKCS5Pading”); //用秘钥初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE,key,zeroIV); //获取解密的数据 byte decyptedData[] =cipher.doFinal(biytMI); //解密数据转换成字符串输出 return new String(decyptedData); } } 2.AES加密和解密 ...

2015年2月10日 · 2 分钟 · 天边的星星

Android FTP客户端实现、Telnet客户端

Android FTP客户端实现 android中使用第三方库来操作FTP,这里使用Apache的包,下载地址为:http://commons.apache.org/proper/commons-net/download_net.cgi 其文件名称为:commons-net-3.3-bin.zip 步骤1:在项目中引入包commons-net-3.3.jar,导入需要的FTPClient类; 步骤2:初始化FTPClient mFtp=new FTPClient(); 步骤3:设置登录的地址和端口 mFtp.connect(ftpUrl,21); 步骤4:设置登录用户名和密码 mFtp.login(name,pwd); 步骤5:设置文件类型和采用被动传输方式 mFtp.setFileType(FTP.BINARY_FILE_TYPE); mFtp.enterLocalPassiveMode(); 步骤6:传输文件 boolean aRtn=mFtp.storeFile(remoteFileName,aInputStream);//成功返回true aInputStream.close(); 步骤7:关闭连接 mFtp.disconnect(); 核心代码: //导入需要的FTPClient类 import org.apache.commons.net.ftp.FTPClient; //初始化FTPClient FTPClient ftpClient=new FTPClient(); try{ //连接到指定的FTP服务器 ftpClient.connect(InetAddress.getByName(SERVER)); //使用用户名和密码登录FTP ftpClient.login(USERNAME,PASSWORD); if(ftpClient.getReplyString().contains(“250”)){ //设置文件类型 ftpClient.setFileType(//默认使用的是ASCII编码的,这里设置为二进制文件 org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE ); //定义一个缓冲区 BufferedInputStream buffIn=null; //将文件加载到缓冲区中 buffIn=new BufferedInputStream(new FileInputStream(FULL_PATH_TO_LOCAL_TYPE)); //设置客户端的PASV模式(客户端主动连服务器:端口用20) ftpClient.enterLocalPassiveMode(); //存储文件。返回是否成功 boolean result=ftpClient.storeFile(localAsset.getFileName,progressInput); //关闭缓冲区 buffIn.close(); //登出 ftpClient.logout(); //断开连接 ftpClient.disconnect(); } }catch(SocketException e){ }catch(UnKnowHostException e){ }catch(IOEception ioe){ } Telnet客户端 实现的远程控制Web服务器。 android使用第三方库Telnet,这里使用Apache的包,下载地址:http://commons.apache.org/proper/commons-net/download_net.cgi 其文件名称为:commons-net-3.3-bin.zip 步骤1:在项目中引入包commons-net-3.3.jar,导入需要的TelnetClient类; 步骤2:初始化TelnetClient tc=new TelnetClient(); 步骤3:打开连接 tc.connect(remoteip,remoteport); 步骤4:读写数据 tc.getInputStream(); tc.getOutputStream(); 步骤5:断开Telnet连接 tc.disconnect(); 核心代码: //定义一个TelnetClient TelnetClient tc=new TelnetClient(); try{ //连接到指定的FTP服务器 tc.connect(remoteip,remoteport); }catch(IOEception ioe){ System.exit(1); } IOUtil.readWrite(tc.getInputStream(),tc.getOutputStream(),System.in,System.out); try{ //断开连接 tc.disconnect(); }catch(IOEception ioe){ ...

2015年2月10日 · 1 分钟 · 天边的星星

android蓝牙

http://wenku.baidu.com/link?url=lAOm_kIF29t-JGoUnKAFSY4BhMP6vv-Cvfx9x1_oVSTZ1QDMm6URT7fhRR8ODX7aBVSX8ffOD0LnI-TX4PaRTqzXPWwJdOhBNXMu0lg214O http://wenku.baidu.com/view/490171b20242a8956bece47d.html?re=view http://wenku.baidu.com/view/cf48328371fe910ef12df827.html http://wenku.baidu.com/view/490171b20242a8956bece47d.html?re=view http://wenku.baidu.com/link?url=lAOm_kIF29t-JGoUnKAFSY4BhMP6vv-Cvfx9x1_oVSTZ1QDMm6URT7fhRR8ODX7aBVSX8ffOD0LnI-TX4PaRTqzXPWwJdOhBNXMu0lg214O android平台包含了蓝牙网络协议栈的支持,允许android设备与其他蓝牙设备相互传输数据。应用层框架提供了API函数来访问蓝牙模块。使用这些API可以让应用程序连接其他蓝牙设备,实现点对点或多点无线传输。 运用蓝牙API,可以实现以下功能: 搜索其他蓝牙设备 查询本地蓝牙适配器中已经配对好的设备 建立RFCOMM协议通道 通过服务端搜索连接到其他设备 与其他设备互相传输数据 管理多个连接 快速阅读 Android蓝牙API可以让应用程序与其他设备传输无线数据。 关键类 BluetoothAdapter BluetoothDevice BluetoothSocket BluetoothServerSocket 相关用例 蓝牙对讲 http://developer.android.com/resources/samples/BluetoothChat/index.html 蓝牙医疗设备(Health Device Profile),比如心率监视器,血压计,温度计等。http://developer.android.com/resources/samples/BluetoothHDP/index.html 目录 [隐藏] 1 基本原理 2 蓝牙权限 3 配置蓝牙 4 获取蓝牙设备 4.1 查询已配对设备 4.2 搜索设备 4.3 开启蓝牙可检测性 5 设备连接 5.1 作为服务端连接 5.2 作为客户端连接 6 连接管理 7 在蓝牙规范协议下工作 7.1 Vendor-specific AT commands 7.2 Health Device Profile 基本原理 本文档描述了如何使用蓝牙API来完成蓝牙通讯的四项必要任务:配置蓝牙、搜索附件未配对或可用的蓝牙设备、连接设备、设备间传输数据。 所有蓝牙API都包含在android.bluetooth包中。以下是建立蓝牙连接需要用到的类和接口的概要: BluetoothAdapter (蓝牙适配器) 表示本地蓝牙适配器(蓝牙收发器). BluetoothAdapter是所有蓝牙活动的起始类. 可用于搜索其他蓝牙设备, 查询已配对设备的列表, 使用MAC地址实例化一个BluetoothDevice对象, 创建BluetoothServerSocket侦听其他设备的连接. BluetoothDevice (蓝牙设备) 表示远程蓝牙设备。可以通过一个BluetoothSocket向它描述的远程设备发起连接,或者该设备的名称、地址、类、连接状态等信息。 BluetoothSocket (蓝牙套接字) 表示一个蓝牙套接字(与TCP Socket类似). 它是设备间的连接点,允许应用程序通过InputStream和OutputStream与其他设备进行数据传输。 BluetoothServerSocket (蓝牙服务端套接字) 表示一个开放的蓝牙服务器, 用于侦听其他设备发过来的连接请求(与TCP ServerSocket类似). 要将两台设备连接起来, 其中一台必须使用这个类开启一个server socket. 当远程蓝牙设备发起对server的连接请求, 如果连接被接受,BluetoothServerSocket将返回一个连接成功的BluetoothSocket对象. BluetoothClass (蓝牙类型) 描述一个蓝牙设备的规格参数和功能。这是一个只读的属性集,定义了该设备的主要和次要设备种类和服务。它不能完全描述该设备的所有特性和服务,常用于判断设备的类型。 BluetoothProfile (蓝牙规范协议) 表示Bluetooth profile的接口. Bluetooth profile是设备间基于蓝牙通讯的接口规范协议。比如Hands-Free(非手持设备) profile。更多关于profiles的说明, 请查看Working with Profiles(在蓝牙规范协议下工作)。 BluetoothHeadset (蓝牙耳机) 提供手机使用蓝牙耳机的支持。同时包含了蓝牙耳机和Hands-Free(v1.5)的profiles. BluetoothA2dp (蓝牙A2dp) 定义高质量音频流如何通过蓝牙连接传输到其他设备。”A2DP”是”Advanced Audio Distribution Profile”的缩写,表示高级音频分发规范协议。 BluetoothHealth (蓝牙医疗设备) 表示为医疗设备提供蓝牙服务的代理类。 BluetoothHealthCallback 这是一个抽象类,用于实现BluetoothHealth的callbacks方法。需要继承此类并实现callback方法才能接收应用程序状态和蓝牙频道状态的变化。 BluetoothHealthAppConfiguration 表示蓝牙医疗第三方应用与远程蓝牙医疗设备连接的配置参数。 BluetoothProfile.ServiceListener (蓝牙规范协议服务侦听) 一个接口类,当服务连接或断开的时候通知BluetoothProfile IPC 客户端。(这是内部服务运行的一个特殊模式)。 蓝牙权限 ...

2015年2月4日 · 13 分钟 · 天边的星星

移动健康设备开源项目收集

https://github.com/search?p=4&q=iHealth&ref=searchresults&type=Repositories&utf8=%E2%9C%93 https://github.com/lfreeman/ihealth https://github.com/Arunmainthan/iHealth https://github.com/oyachai/HearthSim/blob/master/docs/DeckFileSpecification.md https://github.com/house4hack/heartmonitor https://github.com/phishman3579/android-heart-rate-monitor http://sandbox.ihealthlabs.com/dev_documentation_openapidoc.htm iHealth’s http://developer.ihealthlabs.com/index.htm http://www.mi.com/ihealth/#overall http://wenku.baidu.com/link?url=UdozX1eBzPZjrDC2IIbIlvzEi7hS8gXmQkH4RgNBI9FgAorMewSouiEBC9W7RHieklYjQsGaxlRERhtKZpUaxL7j3hctm3PdOKC-SiBxZMG http://www.leiphone.com/news/201406/qardioarm.html http://www.mymumu.com/user.php/Change 爱牵挂老人智能腕表 http://knewone.com/things/ai-qian-gua-lao-ren-zhi-neng-wan-biao-1 http://knewone.com/lists/541baa3631302d2f2c170000 https://github.com/xiaomi https://github.com/XiaoMi/android_tv_metro https://github.com/XiaoMi/galaxy-thrift-api https://github.com/XiaoMi/misound http://www.etcomm.cn/products_hc-201.html 技术问题 http://blog.csdn.net/icyfox_bupt/article/details/25487125 http://blog.csdn.net/junbin_fan/article/details/21982509 http://wiki.eoeandroid.com/Bluetooth

2015年2月4日 · 1 分钟 · 天边的星星

Android4.0 隐藏虚拟按键 实现全屏

Android 4.0 因为项目需要, 要实现屏幕全屏,隐藏虚拟按键,即导航栏 在Android的API 中 To this day, you can hide the status bar on handsets using the [FLAG_FULLSCREEN](http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_FULLSCREEN) flag. In Android 4.0, the APIs that control the system bar’s visibility have been updated to better reflect the behavior of both the system bar and navigation bar: The [SYSTEM_UI_FLAG_LOW_PROFILE](http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_LOW_PROFILE) flag replaces the STATUS_BAR_HIDDEN flag. When set, this flag enables “low profile” mode for the system bar or navigation bar. Navigation buttons dim and other elements in the system bar also hide. Enabling this is useful for creating more immersive games without distraction for the system navigation buttons. The [SYSTEM_UI_FLAG_VISIBLE](http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_VISIBLE) flag replaces the STATUS_BAR_VISIBLE flag to request the system bar or navigation bar be visible. The [SYSTEM_UI_FLAG_HIDE_NAVIGATION](http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_HIDE_NAVIGATION) is a new flag that requests the navigation bar hide completely. Be aware that this works only for the navigation bar used by some handsets (it does not hide the system bar on tablets). The navigation bar returns to view as soon as the system receives user input. As such, this mode is useful primarily for video playback or other cases in which the whole screen is needed but user input is not required `<a href="http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_LOW_PROFILE" target="_blank">SYSTEM_UI_FLAG_LOW_PROFILE</a> 相当于隐藏导航栏` [SYSTEM_UI_FLAG_VISIBLE](http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_VISIBLE) 导航栏显示 `<a href="http://developer.android.com/reference/android/view/View.html#SYSTEM_UI_FLAG_HIDE_NAVIGATION" target="_blank">SYSTEM_UI_FLAG_HIDE_NAVIGATION</a>` 要求导航栏完全隐藏–>但这对部分硬件设备有效 方法一: **[java]** [view plain](http://blog.csdn.net/windownew11/article/details/9427469#)[copy](http://blog.csdn.net/windownew11/article/details/9427469#) <div> </div> <div> <embed id="ZeroClipboardMovie_1" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" type="application/x-shockwave-flash" width="18" height="18" align="middle" name="ZeroClipboardMovie_1"> </embed> </div> </div> - <span class="keyword">package</span> com.example.setbutton; - - <span class="keyword">import</span> android.os.Bundle; - <span class="keyword">import</span> android.app.Activity; - <span class="keyword">import</span> android.view.View; - <span class="keyword">import</span> android.view.Window; - <span class="keyword">import</span> android.view.WindowManager; - <span class="keyword">public</span> <span class="keyword">class</span> MainActivity <span class="keyword">extends</span> Activity { - - Window window; - - <span class="comment">/** Called when the activity is first created. */</span> - <span class="annotation">@Override</span> - <span class="keyword">public</span> <span class="keyword">void</span> onCreate(Bundle savedInstanceState) { - <span class="keyword">super</span>.onCreate(savedInstanceState); - <span class="comment">// main = getLayoutInflater().from(this).inflate(R.layout.main, null);</span> - window = getWindow(); - WindowManager.LayoutParams params = window.getAttributes(); - params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE; - window.setAttributes(params); - - setContentView(R.layout.main); - } - - } ...

2015年2月1日 · 3 分钟 · 天边的星星

Android4.3 蓝牙BLE初步

一、关键概念: **Generic Attribute Profile (GATT)** 通过BLE连接,读写属性类小数据的Profile通用规范。现在所有的BLE应用Profile都是基于GATT的。 **Attribute Protocol (ATT)** GATT是基于ATT Protocol的。ATT针对BLE设备做了专门的优化,具体就是在传输过程中使用尽量少的数据。每个属性都有一个唯一的UUID,属性将以characteristics and services的形式传输。 **Characteristic** Characteristic可以理解为一个数据类型,它包括一个value和0至多个对次value的描述(Descriptor)。 **Descriptor** 对Characteristic的描述,例如范围、计量单位等。 **Service** Characteristic的集合。例如一个service叫做“Heart Rate Monitor”,它可能包含多个Characteristics,其中可能包含一个叫做“heart rate measurement”的Characteristic。 二、角色和职责: Android设备与BLE设备交互有两组角色: 中心设备和外围设备(Central vs. peripheral); GATT server vs. GATT client. Central vs. peripheral: 中心设备和外围设备的概念针对的是BLE连接本身。Central角色负责scan advertisement。而peripheral角色负责make advertisement。 GATT server vs. GATT client: 这两种角色取决于BLE连接成功后,两个设备间通信的方式。 举例说明: 现有一个活动追踪的BLE设备和一个支持BLE的Android设备。Android设备支持Central角色,而BLE设备支持peripheral角色。创建一个BLE连接需要这两个角色都存在,都仅支持Central角色或者都仅支持peripheral角色则无法建立连接。 当连接建立后,它们之间就需要传输GATT数据。谁做server,谁做client,则取决于具体数据传输的情况。例如,如果活动追踪的BLE设备需要向Android设备传输sensor数据,则活动追踪器自然成为了server端;而如果活动追踪器需要从Android设备获取更新信息,则Android设备作为server端可能更合适。 三、权限及feature: 和经典蓝牙一样,应用使用蓝牙,需要声明BLUETOOTH权限,如果需要扫描设备或者操作蓝牙设置,则还需要BLUETOOTH_ADMIN权限: 除了蓝牙权限外,如果需要BLE feature则还需要声明uses-feature: 按时required为true时,则应用只能在支持BLE的Android设备上安装运行;required为false时,Android设备均可正常安装运行,需要在代码运行时判断设备是否支持BLE feature: // Use this check to determine whether BLE is supported on the device. Then // you can selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show(); finish(); } 四、启动蓝牙: 在使用蓝牙BLE之前,需要确认Android设备是否支持BLE feature(required为false时),另外要需要确认蓝牙是否打开。 如果发现不支持BLE,则不能使用BLE相关的功能。如果支持BLE,但是蓝牙没打开,则需要打开蓝牙。 打开蓝牙的步骤: 1、获取BluetoothAdapter BluetoothAdapter是Android系统中所有蓝牙操作都需要的,它对应本地Android设备的蓝牙模块,在整个系统中BluetoothAdapter是单例的。当你获取到它的示例之后,就能进行相关的蓝牙操作了。 获取BluetoothAdapter代码示例如下: // Initializes Bluetooth adapter. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); 注:这里通过getSystemService获取BluetoothManager,再通过BluetoothManager获取BluetoothAdapter。BluetoothManager在Android4.3以上支持(API level 18)。 2、判断是否支持蓝牙,并打开蓝牙 获取到BluetoothAdapter之后,还需要判断是否支持蓝牙,以及蓝牙是否打开。 如果没打开,需要让用户打开蓝牙: private BluetoothAdapter mBluetoothAdapter; … // Ensures Bluetooth is available on the device and it is enabled. If not, // displays a dialog requesting user permission to enable Bluetooth. if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } 五、搜索BLE设备: 通过调用BluetoothAdapter的[startLeScan()](http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#startLeScan(android.bluetooth.BluetoothAdapter.LeScanCallback))搜索BLE设备。调用此方法时需要传入 `<a href="http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.LeScanCallback.html">BluetoothAdapter.LeScanCallback</a>`参数。 因此你需要实现 `<a href="http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.LeScanCallback.html">BluetoothAdapter.LeScanCallback</a>`接口,BLE设备的搜索结果将通过这个callback返回。 由于搜索需要尽量减少功耗,因此在实际使用时需要注意: 1、当找到对应的设备后,立即停止扫描; 2、不要循环搜索设备,为每次搜索设置适合的时间限制。避免设备不在可用范围的时候持续不停扫描,消耗电量。 搜索的示例代码如下: /** * Activity for scanning and displaying available BLE devices. */ public class DeviceScanActivity extends ListActivity { private BluetoothAdapter mBluetoothAdapter; private boolean mScanning; private Handler mHandler; ...

2015年1月27日 · 2 分钟 · 天边的星星

android 蓝牙

android平台包含了蓝牙网络协议栈的支持,允许android设备与其他蓝牙设备相互传输数据。应用层框架提供了API函数来访问蓝牙模块。使用这些API可以让应用程序连接其他蓝牙设备,实现点对点或多点无线传输。 运用蓝牙API,可以实现以下功能: 搜索其他蓝牙设备 查询本地蓝牙适配器中已经配对好的设备 建立RFCOMM协议通道 通过服务端搜索连接到其他设备 与其他设备互相传输数据 管理多个连接 快速阅读 Android蓝牙API可以让应用程序与其他设备传输无线数据。 关键类 BluetoothAdapter BluetoothDevice BluetoothSocket BluetoothServerSocket 相关用例 蓝牙对讲 http://developer.android.com/resources/samples/BluetoothChat/index.html 蓝牙医疗设备(Health Device Profile),比如心率监视器,血压计,温度计等。http://developer.android.com/resources/samples/BluetoothHDP/index.html 目录 [隐藏] 1 基本原理 2 蓝牙权限 3 配置蓝牙 4 获取蓝牙设备 4.1 查询已配对设备 4.2 搜索设备 4.3 开启蓝牙可检测性 5 设备连接 5.1 作为服务端连接 5.2 作为客户端连接 6 连接管理 7 在蓝牙规范协议下工作 7.1 Vendor-specific AT commands 7.2 Health Device Profile 基本原理 本文档描述了如何使用蓝牙API来完成蓝牙通讯的四项必要任务:配置蓝牙、搜索附件未配对或可用的蓝牙设备、连接设备、设备间传输数据。 所有蓝牙API都包含在android.bluetooth包中。以下是建立蓝牙连接需要用到的类和接口的概要: BluetoothAdapter (蓝牙适配器) 表示本地蓝牙适配器(蓝牙收发器). BluetoothAdapter是所有蓝牙活动的起始类. 可用于搜索其他蓝牙设备, 查询已配对设备的列表, 使用MAC地址实例化一个BluetoothDevice对象, 创建BluetoothServerSocket侦听其他设备的连接. BluetoothDevice (蓝牙设备) 表示远程蓝牙设备。可以通过一个BluetoothSocket向它描述的远程设备发起连接,或者该设备的名称、地址、类、连接状态等信息。 BluetoothSocket (蓝牙套接字) 表示一个蓝牙套接字(与TCP Socket类似). 它是设备间的连接点,允许应用程序通过InputStream和OutputStream与其他设备进行数据传输。 BluetoothServerSocket (蓝牙服务端套接字) 表示一个开放的蓝牙服务器, 用于侦听其他设备发过来的连接请求(与TCP ServerSocket类似). 要将两台设备连接起来, 其中一台必须使用这个类开启一个server socket. 当远程蓝牙设备发起对server的连接请求, 如果连接被接受,BluetoothServerSocket将返回一个连接成功的BluetoothSocket对象. BluetoothClass (蓝牙类型) 描述一个蓝牙设备的规格参数和功能。这是一个只读的属性集,定义了该设备的主要和次要设备种类和服务。它不能完全描述该设备的所有特性和服务,常用于判断设备的类型。 BluetoothProfile (蓝牙规范协议) 表示Bluetooth profile的接口. Bluetooth profile是设备间基于蓝牙通讯的接口规范协议。比如Hands-Free(非手持设备) profile。更多关于profiles的说明, 请查看Working with Profiles(在蓝牙规范协议下工作)。 BluetoothHeadset (蓝牙耳机) 提供手机使用蓝牙耳机的支持。同时包含了蓝牙耳机和Hands-Free(v1.5)的profiles. BluetoothA2dp (蓝牙A2dp) 定义高质量音频流如何通过蓝牙连接传输到其他设备。”A2DP”是”Advanced Audio Distribution Profile”的缩写,表示高级音频分发规范协议。 BluetoothHealth (蓝牙医疗设备) 表示为医疗设备提供蓝牙服务的代理类。 BluetoothHealthCallback 这是一个抽象类,用于实现BluetoothHealth的callbacks方法。需要继承此类并实现callback方法才能接收应用程序状态和蓝牙频道状态的变化。 BluetoothHealthAppConfiguration 表示蓝牙医疗第三方应用与远程蓝牙医疗设备连接的配置参数。 BluetoothProfile.ServiceListener (蓝牙规范协议服务侦听) 一个接口类,当服务连接或断开的时候通知BluetoothProfile IPC 客户端。(这是内部服务运行的一个特殊模式)。 蓝牙权限 ...

2015年1月26日 · 6 分钟 · 天边的星星