我想检测蓝牙设备并从我的 android 应用程序中获取检测到设备的蓝牙地址。我的任务是使用我的 android 应用程序中的蓝牙打印机打印账单。
问问题
7880 次
2 回答
7
对于蓝牙搜索活动,您需要以下内容,
在您的 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() );
}
}
};
于 2012-08-21T05:32:28.810 回答
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
希望这可以帮助。
于 2012-08-28T03:38:26.137 回答