zzb-Dream-90Time

本文转自: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);

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-08-31
  • 2022-12-23
  • 2021-12-29
  • 2021-12-26
  • 2022-02-06
猜你喜欢
  • 2021-12-20
  • 2021-07-16
  • 2021-12-18
  • 2021-12-26
  • 2021-12-23
  • 2022-02-20
  • 2022-01-16
相关资源
相似解决方案