gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:33:10 24 4
gpt4 key购买 nike

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

最佳答案

对于蓝牙搜索 Activity ,您需要以下内容,

将权限添加到您的 AndroidManifest.xml

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

需要最低 API 级别 7 和 Android 2.1 版本。

Activity 类,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 );
}

在相同的 Activity 中创建 BroadCastReceiver

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

关于android - 如何检测蓝牙设备并从android应用程序获取检测到的设备的蓝牙地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12048872/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com