Android 蓝牙实例【转】

本文转自:http://www.yiibai.com/android/android_bluetooth.html

在很多方面,蓝牙是一种能够发送或接受两个不同的设备之间传输的数据。 Android平台包含了蓝牙框架,使设备以无线方式与其他蓝牙设备进行数据交换的支持。

Android提供蓝牙API来执行这些不同的操作。

  1. 扫描其他蓝牙设备
  2. 获取配对设备列表
  3. 连接到通过服务发现其他设备

Android提供BluetoothAdapter类蓝牙通信。通过调用创建的对象的静态方法getDefaultAdapter()。其语法如下给出。

private BluetoothAdapter BA;
BA = BluetoothAdapter.getDefaultAdapter();

为了使用设备的蓝牙,调用下列蓝牙ACTION_REQUEST_ENABLE的意图。其语法如下:

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);

除了这个常量,有提供其它的API,支持不同任务的其他常数。它们在下面列出。

Sr.No 常数说明
1 ACTION_REQUEST_DISCOVERABLE
此常数用于开启蓝牙的发现
2 ACTION_STATE_CHANGED
此常量将通知蓝牙状态已经改变
3 ACTION_FOUND
此常数用于接收关于所发现的每个设备的信息

启用了蓝牙功能之后,可以通过调用 getBondedDevices()方法来获取配对设备列表。它返回一组的蓝牙设备。其语法如下:

private Set<BluetoothDevice>pairedDevices;
pairedDevices = BA.getBondedDevices();

除了配对的设备,还有API,让更多蓝牙控制权等方法。它们在下面列出。

Sr.No 方法及说明
1 enable()
这种方法使适配器,如果未启用
2 isEnabled()
如果适配器已启用此方法返回true
3 disable()
该方法禁用适配器
4 getName()
此方法返回的蓝牙适配器的名称
5 setName(String name)
此方法更改蓝牙名称
6 getState()
此方法返回蓝牙适配器的当前状态
7 startDiscovery()
此方法开始蓝牙120秒的发现过程。

示例

这个例子提供了示范BluetoothAdapter类操纵蓝牙,并显示通过蓝牙配对设备列表。

为了试验这个例子,需要在实际设备上运行此程序

步骤 描述
1 使用Android Studio创建Android应用程序,并将其命名为Bluetooth,创建这个项目,确保目标SDK编译在Android SDK的最新版本或使用更高级别的API。
2 修改 src/MainActivity.java 文件中添加代码
3 如果修改所需的布局XML文件 res/layout/activity_main.xml  添加GUI组件
4 修改 res/values/string.xml  文件,并添加必要的字符串常量组件
5 修改 AndroidManifest.xml 添加必要的权限。
6 运行应用程序并选择运行Android的设备,并在其上安装的应用和验证结果。

以下是 src/com.yiibai.bluetooth/MainActivity.java 文件的内容:

package com.example.bluetooth;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

   private Button On,Off,Visible,list;
   private BluetoothAdapter BA;
   private Set<BluetoothDevice>pairedDevices;
   private ListView lv;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      On = (Button)findViewById(R.id.button1);
      Off = (Button)findViewById(R.id.button2);
      Visible = (Button)findViewById(R.id.button3);
      list = (Button)findViewById(R.id.button4);

      lv = (ListView)findViewById(R.id.listView1);

      BA = BluetoothAdapter.getDefaultAdapter();
   }

   public void on(View view){
      if (!BA.isEnabled()) {
         Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(turnOn, 0);
         Toast.makeText(getApplicationContext(),"Turned on"
         ,Toast.LENGTH_LONG).show();
      }
      else{
         Toast.makeText(getApplicationContext(),"Already on",
         Toast.LENGTH_LONG).show();
         }
   }
   public void list(View view){
      pairedDevices = BA.getBondedDevices();

      ArrayList list = new ArrayList();
      for(BluetoothDevice bt : pairedDevices)
         list.add(bt.getName());

      Toast.makeText(getApplicationContext(),"Showing Paired Devices",
      Toast.LENGTH_SHORT).show();
      final ArrayAdapter adapter = new ArrayAdapter
      (this,android.R.layout.simple_list_item_1, list);
      lv.setAdapter(adapter);

   }
   public void off(View view){
      BA.disable();
      Toast.makeText(getApplicationContext(),"Turned off" ,
      Toast.LENGTH_LONG).show();
   }
   public void visible(View view){
      Intent getVisible = new Intent(BluetoothAdapter.
      ACTION_REQUEST_DISCOVERABLE);
      startActivityForResult(getVisible,0);}@Overridepublicboolean onCreateOptionsMenu(Menu menu){// Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);returntrue;}}

这里是 activity_main.xml 文件的内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >

   <ScrollView
      android:id="@+id/scrollView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentBottom="true"
      android:layout_alignParentLeft="true"
      android:layout_alignParentRight="true"
      android:layout_alignParentTop="true" >

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

   <TextView
      android:id="@+id/textView1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="@string/app_name"
      android:textAppearance="?android:attr/textAppearanceLarge" />

   <Button
      android:id="@+id/button1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="on"
      android:text="@string/on" />

   <Button
      android:id="@+id/button2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="visible"
      android:text="@string/Visible" />

   <Button
      android:id="@+id/button3"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="list"
      android:text="@string/List" />

   <Button
      android:id="@+id/button4"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:onClick="off"
      android:text="@string/off" />

   <ListView
      android:id="@+id/listView1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:visibility="visible" >

   </ListView>

   </LinearLayout>
</ScrollView>

</RelativeLayout>

这里是 Strings.xml 文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<resources>

   <string name="app_name">Bluetooth</string>
   <string name="action_settings">Settings</string>
   <string name="hello_world">Hello world!</string>
   <string name="on">Turn On</string>
   <string name="off">Turn Off</string>
   <string name="Visible">Get Visible</string>
   <string name="List">List Devices</string>

</resources>

这里是 AndroidManifest.xml 文件的内容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.yiibai.bluetooth"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.BLUETOOTH"/>
   <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      <activity
         android:name="com.yiibai.bluetooth.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>

</manifest>

让我们试着运行AndroidCapture应用程序。假设你已经连接实际的Android移动设备到计算机。启动应用程序之前,Eclipse会显示如下窗口,选择要运行的Android应用程序的选项。

选择移动设备作为一个选项,然后检查移动设备将显示如下界面:

现在选择打开开启蓝牙。但是当选择它,蓝牙将不会被打开。事实上它会询问许可,以启用蓝牙。

现在,只需要选择设置可见按钮来打开视图。下面的屏幕会出现要求许可才能打开发现120秒。

现在,只要选择列表中的设备选项。它会列出倒在列表视图中的配对设备。就我而言,只有一个配对设备。它如下所示。

现在,只需选择关闭按钮来关闭蓝牙。当关掉蓝牙指示成功切换关闭蓝牙会出现以下消息。

时间: 2024-08-14 09:20:01

Android 蓝牙实例【转】的相关文章

Android蓝牙实例(和单片机蓝牙模块通信)

最近做毕设,需要写一个简单的蓝牙APP进行交互,在网上也找了很多资料,终于给搞定了,这里分享一下^_^. 1.Android蓝牙编程 蓝牙3.0及以下版本编程需要使用UUID,UUID是通用唯一识别码(Universally Unique Identifier),这是一个软件构建的标准,也是被开源基金会组织应用在分布式计算环境领域的一部分.在蓝牙3.0及下一版本中,UUID被用于唯一标识一个服务,比如文件传输服务,串口服务.打印机服务等,如下: #蓝牙串口服务 SerialPortService

ym——物联网入口之一Android蓝牙4.0

如果还有同学不知道蓝牙4.0可以做什么请查看Android+蓝牙 4.0 将带来什么?,现在可以穿戴设备也大多用的是蓝牙4.0,如 智能体质秤,智能手环,智能血压计等等. 安卓4.3(API 18)为BLE的核心功能提供平台支持和API,App可以利用它来发现设备.查询服务和读写特性.相比传统的蓝牙,BLE更显著的特点是低功耗.这一优点使android App可以与具有低功耗要求的BLE设备通信,如近距离传感器.心脏速率监视器.健身设备等. 关键术语和概念 Generic Attribute P

Android 蓝牙API详解

随着近两年可穿戴式产品逐渐进入人们的生活,蓝牙开发也成为了Android开发的一个重要模块,下面我们就来说一说蓝牙的这些API. 1.蓝牙开发有两个主要的API: BuletoothAdapter:本地蓝牙的适配器,也就是说当前应用程序所运行的Android设备上的蓝牙 BuletoothDevice  : 远程的蓝牙适配器,也就是说你要连接的Android设备的适配器. 2.蓝牙权限 : android.permission.BLUETOOTH : 允许程序连接到已配对的蓝牙设备, 请求连接/

【Android应用开发】Android 蓝牙低功耗 (BLE) ( 第一篇 . 概述 . 蓝牙低功耗文档 翻译)

转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/50515359 参考 :  -- 官方文档 : https://developer.android.com/guide/topics/connectivity/bluetooth-le.html; 1. 概述 BLE 概述 : -- 版本支持 : Android 4.3 (API Level 18) 内置框架引入了 蓝牙低功耗方案 (Bluetooth Low Energy,

Android蓝牙4.0之玩爆智能穿戴、家具(二)【进阶篇】

闲话中心 这几天最大的事可能就是美国总统的上任,双十一,还有乐视股价了,乍一看,好像和我们没什么关系,其实肯定是有的了,要不然他也成不了新闻啊,有一点我们得改变,就是我们必须要希望我们自己国家的企业能过强大,我们必须支持他们,哪怕他做的不够好,这个问题其实就像一个国家一样,我们都知道许多政策是不合理的,或者说有很多制度是坑人的,但是我们不能因为这些而不爱我们的国家,那么企业也是一样,就拿乐视来说,股价跌了,公司遇到资金问题了,你看看这些媒体都在报道什么,全是负面消息,马上倒闭了,或者说是撑不住了

Android 蓝牙开发之搜索、配对、连接、通信大全

        蓝牙( Bluetooth®):是一种无线技术标准,可实现固定设备.移动设备和楼宇个人域网之间的短距离数据 交换(使用2.4-2.485GHz的ISM波段的UHF无线电波).蓝牙设备最多可以同时和7个其它蓝牙设备建立连接,进 行通信,当然并不是每一个蓝牙都可以达到最大值.下面,我们从蓝牙的基本概念开始,一步一步开始了解蓝牙. 基本概念: 安卓平台提供对蓝牙的通讯栈的支持,允许设别和其他的设备进行无线传输数据.应用程序层通过安卓API来调用蓝牙的相关功 能,这些API使程序无线连接

Android 蓝牙通信

Android 蓝牙传文件比较常见,但是官方也给出了基于蓝牙通讯做了个聊天室的sample,BluetoothChat.有兴趣的可以下载看下,很有意思.通讯那块用了特殊的BluetoothSocket.思路跟一般socket通讯一样.必须有服务端和客户端.sample有三个类:BluetoothChat,BluetoothChatService,DeviceListActivity. BluetoothChat是主界面,可以看到聊天的内容,BluetoothChatService是功能类,实现了

android蓝牙(二)——接收数据

在蓝牙开发中,我们有这样的一个需求:我们的android客户端要始终保持和蓝牙的连接,当蓝牙有数据返回的时候,android客户端就要及时的收取数据,当蓝牙没有数据返回的时候我们就要保持android客户端和蓝牙之间的连接.这个时候我们就要采取socket来实现和蓝牙之间的连接.做项目使用过http轮询去获取数据,但是发现那样总是有一定的弊端.于是就才用了socket方式去获取数据. 实现步骤:1.启动一个service去监听是否有数据返回.一旦有数据返回就启动一个线程去处理数据 2.处理完数据

Android蓝牙自动配对Demo,亲测好使!!!

蓝牙自动配对,即搜索到其它蓝牙设备之后直接进行配对,不需要弹出配对确认框或者密钥输入框. 转载请注明出处http://blog.csdn.net/qq_25827845/article/details/52400782 经过最近一段时间得研究,针对网上给出的案例.总结了一个亲测好使的Demo. 说明如下: 1.本Demo用来连接蓝牙设备HC-05,如果你要连接其他蓝牙设备,注意修改相关名字以及修改设备初试pin值. 2.将Demo安装在Android手机上,点击按钮,可以实现与目标蓝牙设备的自动