Android 扫描周围蓝牙设备

package com.zhoucj.bluetooth;

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.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button bluetoothBtn;
    BluetoothAdapter adapter;//本地蓝牙适配器
    //BluetoothDevice device;//远程蓝牙适配器
    BluetoothReceiver bluetoothReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bluetoothBtn=(Button)findViewById(R.id.bluetooth);
        bluetoothBtn.setOnClickListener(listener);
        
        //创建一个IntentFilter对象,将action指定为 BluetoothDevices.ACTION_FOUND;
        IntentFilter intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
        bluetoothReceiver=new BluetoothReceiver();
        //注册广播接收器
        registerReceiver(bluetoothReceiver, intentFilter);
        //获取本地蓝牙适配器
        adapter=BluetoothAdapter.getDefaultAdapter();
        
        
    }

    //广播接收器
    private class BluetoothReceiver extends 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);
                Log.i("msg", device.getAddress());
                
            }
            
        }
        
    }
    
    private OnClickListener listener=new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if(adapter!=null)
            {
                //开始扫描周围的蓝牙设备
                //如果扫描到蓝牙设备,通过广播接收器发送广播
                adapter.startDiscovery();
            }else
            {
                Log.i("msg", "没有蓝牙设备");
            }
        }
    };
    

    
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        //卸载广播接收器
        unregisterReceiver(bluetoothReceiver);
    }



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

}

最后加上

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

代码中都有注释,

posted @ 2013-10-28 22:40  最後的輕語  阅读(1000)  评论(0编辑  收藏  举报