Android Bluetooth(蓝牙)实例

在很多方面,蓝牙是一种能够发送或接受两个不同的设备之间传输的数据。 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);

   }
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
   }

}

这里是 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应用程序的选项。

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

Anroid Bluetooth Tutorial

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

Anroid Bluetooth Tutorial

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

Anroid Bluetooth Tutorial

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

Anroid Bluetooth Tutorial

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

Anroid Bluetooth Tutorial

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Android Studio 蓝牙实例可以通过以下步骤实现: 1. 在 AndroidManifest.xml 文件中添加蓝牙权限: ``` <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> ``` 2. 在布局文件中添加一个按钮,用于启动蓝牙: ``` <Button android:id="@+id/btn_enable_bluetooth" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="启动蓝牙" /> ``` 3. 在 Activity 中添加以下代码,用于启动蓝牙: ``` private BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 获取 BluetoothAdapter 对象 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 获取启动蓝牙的按钮 Button btnEnableBluetooth = findViewById(R.id.btn_enable_bluetooth); // 设置按钮点击事件 btnEnableBluetooth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 如果蓝牙未启动,则启动蓝牙 if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // 处理启动蓝牙的结果 if (requestCode == REQUEST_ENABLE_BT) { if (resultCode == RESULT_OK) { // 蓝牙已启动 Toast.makeText(this, "蓝牙已启动", Toast.LENGTH_SHORT).show(); } else { // 用户拒绝启动蓝牙 Toast.makeText(this, "用户拒绝启动蓝牙", Toast.LENGTH_SHORT).show(); } } } ``` 以上就是一个简单的 Android Studio 蓝牙实例。当用户点击启动蓝牙的按钮时,会弹出系统的蓝牙启动对话框,用户可以选择启动或拒绝启动蓝牙。如果用户选择启动蓝牙,则会显示一个提示信息,表示蓝牙已启动。如果用户拒绝启动蓝牙,则会显示一个提示信息,表示用户拒绝启动蓝牙。 ### 回答2: Android Studio 中使用蓝牙功能需要通过蓝牙 API 来实现,其中最常用的是 BluetoothAdapter 和 BluetoothSocket。下面我们来简单介绍一下如何使用这两个类来实现蓝牙通讯,建立连接以及传输数据的过程。 一、获取蓝牙 Adapter 对象 在 Android 中可以通过 BluetoothAdapter 类获取手机的蓝牙 Adapter 对象,我们可以通过以下代码获取蓝牙 Adapter: ```java BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); ``` 二、扫描周围的蓝牙设备 在获取到蓝牙 Adapter 对象后,我们可以使用 startDiscovery() 方法来开始扫描周围的蓝牙设备。扫描到的设备会以广播的形式发送到你的手机,我们需要注册 BroadcastReceiver 来接收这些广播。具体实现可以参考下面的代码: ``` // 开始扫描蓝牙设备 mBluetoothAdapter.startDiscovery(); // 广播接收者,接收蓝牙设备扫描结果 private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 获取发现的蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 处理扫描到的设备信息 ... } } }; // 注册广播接收者 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); ``` 三、建立蓝牙连接 在扫描到目标蓝牙设备后,我们就可以使用 BluetoothSocket 类来建立蓝牙连接。请注意,在建立连接之前,我们需要使用 createBond() 方法来配对设备。 ``` // 配对蓝牙设备 device.createBond(); // 建立蓝牙连接 BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID); socket.connect() ``` 四、蓝牙数据传输 在建立连接之后,我们就可以使用输入流和输出流来进行数据传输了。输出流用于发送数据,输入流用于接收数据。具体实现可以参考以下代码: ``` // 获取输入输出流 InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); // 发送数据 os.write(data.getBytes()); // 接收数据 byte[] buffer = new byte[1024]; int length = is.read(buffer); String data = new String(buffer, 0, length); ``` 以上就是 Android Studio 蓝牙实例的基本实现过程,建立连接并传输数据不过是其中的一小部分,具体的实现过程还需要根据具体的需求进行调整。 ### 回答3: Android Studio 是一个让开发者在 Android 系统上开发应用程序的集成开发环境。在 Android 应用程序中,蓝牙通信是一项非常常见的功能,有时候我们需要在应用程序中实现与其它设备之间的数据交换,这就需要使用到蓝牙通信。这里将为大家介绍如何使用Android Studio实现蓝牙通信的基础操作。 首先我们需要创建一个基本的 Android 应用程序,然后在布局文件中添加一个按钮,用于触发与蓝牙设备的连接。然后在 MainActivity 类中添加一些必要的代码,开启蓝牙并使用 Intent 连接到设备。 在 onCreate 函数中,我们需要检查当前设备是否支持蓝牙,如果设备支持蓝牙,我们需要启用它,以便应用程序可以与设备上的蓝牙通信。为了启用蓝牙,我们需要使用 BluetoothAdapter 类,其中的 isEnabled() 方法可以检查蓝牙是否已经启用。如果 isEnabled() 返回 false,则需要启用蓝牙,这可以通过调用 startActivityForResult() 方法来实现。 在 onActivityResult 函数中,我们可以获取与蓝牙设备的连接状态,以确定是否已成功连接到目标设备。通过检查返回的 resultCode 和 requestCode 值,我们可以确定是否连接成功或失败。如果连接成功,则可以开始进行数据通信,否则需要重新连接。 一旦与蓝牙设备连接成功,我们就可以开始进行数据通信。根据使用情况,我们可以使用输入流和输出流来发送和接收数据。要发送数据,我们可以直接使用输出流,使用 write(byte[]) 函数将数据写入缓冲区。在接收数据时,我们需要使用输入流来读取数据,使用 read() 函数将缓冲区中的数据读取出来,并将其显示到应用程序中。 在蓝牙通信中,还需要注意一些问题,如蓝牙硬件的限制、连接状态的管理、数据加密等。特别是在数据通信时,需要特别小心,以免数据传输出现错误或泄漏敏感信息。 总之,使用 Android Studio 实现蓝牙通信是一项非常实用的技能,可以让我们更好地控制设备之间的数据交换,并实现更多的应用程序功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值