首页 > 代码库 > 搜索附近的蓝牙设备,并将其名字和mac地址现在在textview中

搜索附近的蓝牙设备,并将其名字和mac地址现在在textview中

上一篇文章已经写了如何打开蓝牙设备,显示已经配对成功的蓝牙设备,http://blog.csdn.net/liuzuyi200/article/details/37740401

这篇文章主要写如何搜索蓝牙设备

(2)搜索蓝牙设备需要执行startDiscovery()这个方法,这个过程会大约持续12秒。

if (mBluetoothAdapter.isDiscovering()) {  
				            mBluetoothAdapter.cancelDiscovery();  
				        }  
				        // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回  
				        mBluetoothAdapter.startDiscovery();  
要执行这个方法必须注册一个BroadcastReceiver,属性BluetoothDevice.ACTION_FOUND的intent 

private final BroadcastReceiver Receiver = new BroadcastReceiver(){

     	public void onReceive(Context context, Intent intent) {
     		String action = intent.getAction();
     		if(BluetoothDevice.ACTION_FOUND.equals(action))
     		{
     			BluetoothDevice device =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);	
     			 if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
                             
     				textview1.append(device.getName() + ":"  
                            + device.getAddress() + "\n\n");
                 }  
     			
     		}	
		}
	};
注册BroadcastReceiver用下面这句话完成,分别在调用开始和结束时使用
 
IntentFilter Filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
	        registerReceiver( Receiver , Filter); 
	         
	     Filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
	        registerReceiver( Receiver , Filter);  
如果调用结束,还需要取消注册

protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
        //解除注册  
        unregisterReceiver(Receiver);  
    } 
下面是打开蓝牙设备 显示已经配对的蓝牙设备 ,搜索附近的蓝牙设备,并将已配对的蓝牙设备显示在textview中的布局文件和源码

activity_main.xml

<ScrollView 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">
<LinearLayout 
   
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

    <TextView
        android:id="@+id/Textview1"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>
</ScrollView>
MainActivity

package com.liuzuyi.bluetooth;

import java.util.Set;

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.os.Bundle;
import android.os.Parcelable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final int REQUEST_ENABLE_BT = 1;

	private Button button;
	private TextView textview1;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		button=(Button)findViewById(R.id.button1);
        textview1=(TextView )findViewById(R.id.Textview1);
		button.setOnClickListener( new blue());	
		 IntentFilter Filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);  
	        registerReceiver( Receiver , Filter); 
	         
	      Filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);  
	        registerReceiver( Receiver , Filter);  
		
	}
	private final BroadcastReceiver Receiver = new BroadcastReceiver(){

     	public void onReceive(Context context, Intent intent) {
     		String action = intent.getAction();
     		if(BluetoothDevice.ACTION_FOUND.equals(action))
     		{
     			BluetoothDevice device =intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);	
     			 if (device.getBondState() != BluetoothDevice.BOND_BONDED) {  
                             
     				textview1.append(device.getName() + ":"  
                            + device.getAddress() + "\n\n");
                 }  
     			
     		}	
		}
	};
	protected void onDestroy() {  
        // TODO Auto-generated method stub  
        super.onDestroy();  
        //解除注册  
        unregisterReceiver(Receiver);  
    }  
	class blue implements OnClickListener{
		
		@Override
		public void onClick(View v) {
			
			  BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
				if (mBluetoothAdapter == null) 
				{
				   Toast.makeText(MainActivity.this, "此设备不支持蓝牙传输功能!", Toast.LENGTH_SHORT).show();
				}
				else{	
					Toast.makeText(MainActivity.this, "此设备支持蓝牙传输功能!", Toast.LENGTH_SHORT).show();
					if (!mBluetoothAdapter.isEnabled()) 
					{
						  Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
						  enableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);  
				            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				           Toast.makeText(MainActivity.this, "蓝牙设备已经打开!", Toast.LENGTH_SHORT).show(); 
				         
			        }
					 if (mBluetoothAdapter.isDiscovering()) {  
				            mBluetoothAdapter.cancelDiscovery();  
				        }  
				        // 开始搜索蓝牙设备,搜索到的蓝牙设备通过广播返回  
				        mBluetoothAdapter.startDiscovery();  
				     
					Set<BluetoothDevice> pairedDevices=mBluetoothAdapter.getBondedDevices();
					if(pairedDevices.size() > 0){
						for (BluetoothDevice bluetoothDevice : pairedDevices) {
							textview1.append(bluetoothDevice.getName() + ":"  
				                        + bluetoothDevice.getAddress() + "\n\n");
						}
					}
				  }			
		      }		
	}
}

说明:点击按钮,就会把未配对过的蓝牙设备的名字和mac地址显示在textview中,如果想显示所有的蓝牙设备就把onReceive方法中的if语句去掉。