我发现我们可以使用BluetoothManager通过以下代码获取连接的蓝牙设备:
BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
List<BluetoothDevice> connected = manager.getConnectedDevices(GATT);
Log.i("Connected Devices: ", connected.toString()+"");
但是,我得到“无法解析符号'GATT'”。应该做什么?
更新:
package in.justrobotics.jrbluetoothcontrol;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.List;
public class TerminalActivity extends AppCompatActivity {
TextView connectedDevices;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_terminal);
connectedDevices=(TextView) findViewById(R.id.connected_devices);
BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
List<BluetoothDevice> connected = manager.getConnectedDevices(BluetoothGatt.GATT);
// if (connected.size()>=1) {
Log.i("Connected Devices: ", connected.get(0).toString() + "");
connectedDevices.setText(connected.get(0).toString());
// }
}
}
我的应用程序因以下错误而崩溃:
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.justrobotics.jrbluetoothcontrol/in.justrobotics.jrbluetoothcontrol.TerminalActivity}: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2706)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1514)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Caused by: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at in.justrobotics.jrbluetoothcontrol.TerminalActivity.onCreate(TerminalActivity.java:24)
at android.app.Activity.performCreate(Activity.java:6875)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2659)
... 9 more
即使我有一个通过BT连接的扬声器。
相反,如果有人可以为我回答这个问题,那就更好了:Get address of connected device bluetooth
最佳答案
import static android.bluetooth.BluetoothProfile.GATT;
关于android - 获取连接的设备地址蓝牙,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51221881/