繁体   English   中英

发现蓝牙设备

[英]discovering bluetooth devices

此代码用于搜索和发现蓝牙设备
我在BroadcastReceiver上做Toast他们甚至不显示它(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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM