此代码用于搜索和发现蓝牙设备
我在BroadcastReceiver上做烤面包片,他们甚至不显示它
(Android 7猜测权限中的问题,我只是将其放在mainfist上)
Button button;
ListView listView;
BluetoothAdapter mBluetoothAdapter;
Integer requestbluetooth=1;
ArrayList<String> arrayList;
ArrayAdapter<String> Adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList =new ArrayList<>();
button=findViewById(R.id.printButton);
listView=findViewById(R.id.listView);
Adapter = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(Adapter);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
mBluetoothAdapter.startDiscovery();
}
});
}
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress();
arrayList.add(deviceName);
Adapter.notifyDataSetChanged();
}
}
};
答案 0 :(得分:0)
从Android 6.0(API级别23)开始,您必须在运行时请求权限。大多数应用程序都是在用户首次启动应用程序时执行的。
要检查您是否已经拥有权限,请使用
int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_SMS);
要请求权限,请使用
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_SMS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);