此代码用于搜索和发现蓝牙设备
我在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();
                }
            }
        };

最佳答案

从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);

09-26 00:03