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

时间:2012-08-21 05:25:03

标签: android printing bluetooth

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

2 个答案:

答案 0 :(得分:6)

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

将权限添加到AndroidManifest.xml

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

需要最低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 );
}           

在同一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() );
        }
    }
};

答案 1 :(得分:1)

一旦找到设备,我希望你需要连接它。

下面是一个类似于上面发布的示例,但它也打印出每个设备上的服务。

http://digitalhacksblog.blogspot.com/2012/05/android-example-bluetooth-discover-and.html

我没有连接打印机的任何示例,但我有一个连接设备和发送数据的示例,这可能会有所帮助。第一个是连接到运行SPP服务器的Windows PC,第二个是连接到Arduino。

http://digitalhacksblog.blogspot.com/2012/05/android-example-bluetooth-simple-spp.html http://digitalhacksblog.blogspot.com/2012/05/arduino-to-android-turning-led-on-and.html

希望这有帮助。