个性化阅读
专注于IT技术分析

android蓝牙教程

点击下载

本文概述

蓝牙是一种与其他设备无线交换数据的方式。 Android提供了蓝牙API来执行一些任务,例如:

  • 扫描蓝牙设备
  • 连接和从其他设备传输数据
  • 管理多个连接等

Android蓝牙API

android.bluetooth包提供了许多与蓝牙一起使用的接口类,例如:

  • 蓝牙适配器
  • 蓝牙设备
  • 蓝牙插座
  • 蓝牙服务器插座
  • 蓝牙类
  • 蓝牙配置文件
  • BluetoothProfile.ServiceListener
  • 蓝牙耳机
  • 蓝牙A2dp
  • 蓝牙健康
  • 蓝牙健康回调
  • BluetoothHealthApp配置

BluetoothAdapter类

在BluetoothAdapter类的帮助下,我们可以执行一些基本任务,例如启动设备发现,查询已配对(绑定)的设备列表,创建BluetoothServerSocket实例以侦听连接请求等。

BluetoothAdapter类的常量

BluetoothAdapter类提供了许多常量。其中一些如下:

  • 字符串ACTION_REQUEST_ENABLE
  • 字符串ACTION_REQUEST_DISCOVERABLE
  • 字符串ACTION_DISCOVERY_STARTED
  • 字符串ACTION_DISCOVERY_FINISHED

BluetoothAdapter类的方法

BluetoothAdapter类的常用方法如下:

  • 静态同步BluetoothAdapter getDefaultAdapter()返回BluetoothAdapter的实例。
  • boolean enable()启用蓝牙适配器(如果已禁用)。
  • 如果启用了蓝牙适配器,则boolean isEnabled()返回true。
  • boolean disable()禁用蓝牙适配器(如果已启用)。
  • 字符串getName()返回蓝牙适配器的名称。
  • boolean setName(String name)更改蓝牙名称。
  • int getState()返回本地蓝牙适配器的当前状态。
  • Set <BluetoothDevice> getBondedDevices()返回一组配对(绑定)的BluetoothDevice对象。
  • boolean startDiscovery()启动发现过程。

Android蓝牙示例:以编程方式启用,禁用并使蓝牙变得可辨别

你只需要编写几行代码即可启用或禁用蓝牙。

activity_main.xml

从面板上拖动一个textview和三个按钮,现在activity_main.xml文件将如下所示:

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView android:text=""
     android:id="@+id/out" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content">
    </TextView>
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="49dp"
        android:text="TURN_ON" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="27dp"
        android:text="DISCOVERABLE" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button2"
        android:layout_below="@+id/button2"
        android:layout_marginTop="28dp"
        android:text="TURN_OFF" />

</RelativeLayout>

提供权限

你需要在AndroidManifest.xml文件中提供以下权限。

<uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

AndroidManifest.xml文件的完整代码如下。

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <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.example.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>

活动类

让我们编写代码以启用,禁用并使蓝牙可发现。

package com.example.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
      private static final int REQUEST_ENABLE_BT = 0;
      private static final int REQUEST_DISCOVERABLE_BT = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    final TextView out=(TextView)findViewById(R.id.out);
    final Button button1 = (Button) findViewById(R.id.button1);
    final Button button2 = (Button) findViewById(R.id.button2);
    final Button button3 = (Button) findViewById(R.id.button3);
    final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
       out.append("device not supported");
    }
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
    });
    button2.setOnClickListener(new View.OnClickListener() {
     @Override
        public void onClick(View arg0) {
            if (!mBluetoothAdapter.isDiscovering()) {
                  //out.append("MAKING YOUR DEVICE DISCOVERABLE");
                   Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE", Toast.LENGTH_LONG);

                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);
                  
            }
        }
    });
    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {   
            mBluetoothAdapter.disable();
            //out.append("TURN_OFF BLUETOOTH");
            Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_LONG);
         
            }
    });
}

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

}


你需要在真实设备(例如移动设备)上运行它以测试应用程序。


android蓝牙教程的下一个主题:

android蓝牙列表配对设备示例

赞(0)
未经允许不得转载:srcmini » android蓝牙教程

评论 抢沙发

评论前必须登录!