如何检测蓝牙设备并从Android应用程序获取检测到的设备的蓝牙地址

Ano*_* ka 1 printing android bluetooth

我想检测蓝牙设备并从我的Android应用程序获取检测到的设备的蓝牙地址.我的任务是从我的Android应用程序使用蓝牙打印机打印帐单.

Luc*_*fer 7

对于蓝牙搜索活动,您需要以下内容:

将权限添加到AndroidManifest.xml中

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)

最低API级别7和Android 2.1版本是必需的.

活动类,onCreate()方法

private static BluetoothAdapter mBtAdapter;

// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);

// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);


filter = new IntentFilter( BluetoothAdapter.ACTION_DISCOVERY_STARTED );
this.registerReceiver( mReceiver, filter );

// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();


if ( !mBtAdapter.isEnabled()) 
{
    Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT );
}           
Run Code Online (Sandbox Code Playgroud)

BroadCastReceiver同样创造Activity

private final BroadcastReceiver mReceiver = new BroadcastReceiver() 
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        try
        {
            String action = intent.getAction();

            // When discovery finds a device
            if ( BluetoothDevice.ACTION_FOUND.equals(action) ) 
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                String deviceName = device.getName();
                String deviceAddress = device.getAddress();

                            System.out.println ( "Address : " + deviceAddress );
            } 
        }
        catch ( Exception e )
        {
            System.out.println ( "Broadcast Error : " + e.toString() );
        }
    }
};
Run Code Online (Sandbox Code Playgroud)