Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 藍牙通信-搜索附近的藍牙設備

藍牙通信-搜索附近的藍牙設備

編輯:關於Android編程

 與其他設備通信通信之前需要搜索周圍的藍牙設備。

怎麼搜索呢??

1.如果數據中已經和某些藍牙設備綁定,可以使用BluetoothAdapter.getBondedDevices();方法獲得已經綁定的藍牙設備列表

2.搜索周圍的藍牙設備受用BluetoothAdapter.startDiscovery()方法

3.搜索到的藍牙設備都是通過廣播返回,so..。需要注冊廣播接收器來獲得已經搜索到的藍牙設備。

下面我們看一下demo:

我們在布局文件中放一個按鈕和一個顯示文本TextView。

我們點擊Button時,開始搜索附近的藍牙設備。將搜索到的藍牙設備追加到TextView上,我們將綁定的和搜索到的都顯示在TextView上。

布局文件:


[html]
<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" > 
 
    <Button 
        android:id="@+id/button_id" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:onClick="onClick_Search" 
        android:text="搜索藍牙設備" /> 
 
    <TextView 
        android:id="@+id/tvDevices" 
        android:layout_width="fill_parent" 
        android:layout_below="@+id/button_id" 
        android:layout_height="wrap_content" /> 
 
</RelativeLayout> 

<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" >

    <Button
        android:id="@+id/button_id"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick_Search"
        android:text="搜索藍牙設備" />

    <TextView
        android:id="@+id/tvDevices"
        android:layout_width="fill_parent"
        android:layout_below="@+id/button_id"
        android:layout_height="wrap_content" />

</RelativeLayout>

 

 


JAVA文件:

[java]
package com.example.search_bluetooth_devices; 
 
import java.util.Set; 
 
import android.os.Bundle; 
import android.app.Activity; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.view.Menu; 
import android.view.View; 
import android.view.Window; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
    private TextView mTextView; 
    private BluetoothAdapter mBluetoothAdapter; 
 
    private BroadcastReceiver mReceiver = new BroadcastReceiver() { 
 
        @Override 
        public void onReceive(Context context, Intent intent) { 
            // TODO Auto-generated method stub  
 
            String action = intent.getAction(); 
            // 獲得已經搜索到的藍牙設備  
            if (action.equals(BluetoothDevice.ACTION_FOUND)) { 
                BluetoothDevice device = intent 
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 
                // 搜索到的不是已經綁定的藍牙設備  
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) { 
                    // 顯示在TextView上  
                    mTextView.append(device.getName() + ":" 
                            + device.getAddress()+"\n"); 
                } 
                // 搜索完成  
            } else if (action 
                    .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { 
                setProgressBarIndeterminateVisibility(false); 
                setTitle("搜索藍牙設備"); 
            } 
        } 
    }; 
 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); 
 
        setContentView(R.layout.activity_main); 
 
        mTextView = (TextView) findViewById(R.id.tvDevices); 
 
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
        // 獲取所有已經綁定的藍牙設備  
        Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices(); 
        if (devices.size() > 0) { 
            for (BluetoothDevice bluetoothDevice : devices) { 
                mTextView.append(bluetoothDevice.getName() + ":" 
                        + bluetoothDevice.getAddress() + "\n\n"); 
            } 
        } 
        // 注冊用以接收到已搜索到的藍牙設備的receiver  
        IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
        registerReceiver(mReceiver, mFilter); 
        // 注冊搜索完時的receiver  
        mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); 
        registerReceiver(mReceiver, mFilter); 
    } 
 
    @Override 
    protected void onDestroy() { 
        // TODO Auto-generated method stub  
        super.onDestroy(); 
        //解除注冊  
        unregisterReceiver(mReceiver); 
    } 
 
    @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; 
    } 
 
    public void onClick_Search(View v) { 
        setProgressBarIndeterminateVisibility(true); 
        setTitle("正在掃描...."); 
        // 如果正在搜索,就先取消搜索  
        if (mBluetoothAdapter.isDiscovering()) { 
            mBluetoothAdapter.cancelDiscovery(); 
        } 
        // 開始搜索藍牙設備,搜索到的藍牙設備通過廣播返回  
        mBluetoothAdapter.startDiscovery(); 
    } 
 

package com.example.search_bluetooth_devices;

import java.util.Set;

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

public class MainActivity extends Activity {

 private TextView mTextView;
 private BluetoothAdapter mBluetoothAdapter;

 private BroadcastReceiver mReceiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub

   String action = intent.getAction();
   // 獲得已經搜索到的藍牙設備
   if (action.equals(BluetoothDevice.ACTION_FOUND)) {
    BluetoothDevice device = intent
      .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
    // 搜索到的不是已經綁定的藍牙設備
    if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
     // 顯示在TextView上
     mTextView.append(device.getName() + ":"
       + device.getAddress()+"\n");
    }
    // 搜索完成
   } else if (action
     .equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
    setProgressBarIndeterminateVisibility(false);
    setTitle("搜索藍牙設備");
   }
  }
 };

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

  setContentView(R.layout.activity_main);

  mTextView = (TextView) findViewById(R.id.tvDevices);

  mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  // 獲取所有已經綁定的藍牙設備
  Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
  if (devices.size() > 0) {
   for (BluetoothDevice bluetoothDevice : devices) {
    mTextView.append(bluetoothDevice.getName() + ":"
      + bluetoothDevice.getAddress() + "\n\n");
   }
  }
  // 注冊用以接收到已搜索到的藍牙設備的receiver
  IntentFilter mFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  registerReceiver(mReceiver, mFilter);
  // 注冊搜索完時的receiver
  mFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  registerReceiver(mReceiver, mFilter);
 }

 @Override
 protected void onDestroy() {
  // TODO Auto-generated method stub
  super.onDestroy();
  //解除注冊
  unregisterReceiver(mReceiver);
 }

 @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;
 }

 public void onClick_Search(View v) {
  setProgressBarIndeterminateVisibility(true);
  setTitle("正在掃描....");
  // 如果正在搜索,就先取消搜索
  if (mBluetoothAdapter.isDiscovering()) {
   mBluetoothAdapter.cancelDiscovery();
  }
  // 開始搜索藍牙設備,搜索到的藍牙設備通過廣播返回
  mBluetoothAdapter.startDiscovery();
 }

}

配置文件:


[html] view plaincopyprint?<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.search_bluetooth_devices" 
    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.example.search_bluetooth_devices.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> 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.search_bluetooth_devices"
    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.example.search_bluetooth_devices.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>

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved