1. AndroidManifest.xml permission

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

2. Get BlueToothAdapter
mBtAdapter = BluetoothAdapter.getDeafultAdapter();


3. Discovery
mBtAdapter.startDiscovery();


4. Device Broadcast
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstranceState);

    intentFilter filter = new intentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);
    filter = new intentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINSIHSED);
    this.registerReciver(mReceiver, filter);
}

private final BroadcastRecevier mReceiver = new BroadcastReceiver(){
    public void onReceiver(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){
                mNewDevicesArrayAdater.add(device.getName() + "\n" + device.getAddress());
            }
        }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
            setProgressBarIndeterminateVisibility(false);
            setTitle(R.string.select_device);
            if(mNewDevicesArrayAdapter.getCount() == 0){
                String noDevices = getText(R.string.non_found).toString();
                mNewDevicesArrayAdapter.add(noDevices);
            }
        }
};

5.mAdapter.cacnelDiscovery();

BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

private static final UUID MY_UUID = UUID.fromString("00001108-0000-1000-8000-00805F9B34FB");
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);

 

mmSocket.connect();

創作者介紹
創作者 shadow 的頭像
shadow

資訊園

shadow 發表在 痞客邦 留言(0) 人氣()