Bluetoothデバイスを検出し、Androidアプリから検出されたデバイスのBluetoothアドレスを取得したい。私の仕事は、AndroidアプリのBluetoothプリンターを使用して請求書を印刷することです。
2 に答える
Bluetooth 検索アクティビティには、次のものが必要です。
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() );
}
}
};
デバイスが見つかったら、それに接続する必要があると思います。
以下は上記と同様の例ですが、各デバイスのサービスも出力されます。
http://digitalhacksblog.blogspot.com/2012/05/android-example-bluetooth-discover-and.html
プリンターに接続する例はありませんが、デバイスに接続してデータを送信する例はあります。1 つ目は SPP サーバーを実行している Windows PC に接続し、2 つ目は 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
お役に立てれば。