简体   繁体   English

发现蓝牙设备

[英]discovering bluetooth devices

this code for search and discovering bluetooth devices 此代码用于搜索和发现蓝牙设备
i make Toast on BroadcastReceiver they don't even show it (android 7 a guess the issue in permission i just put it on mainfist) 我在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();
                }
            }
        };

Since Android 6.0 (API level 23) you have to request the permissions at runtime. 从Android 6.0(API级别23)开始,您必须在运行时请求权限。 Most application do that when the user is starting the app for the first time. 用户首次启动应用程序时,大多数应用程序都会这样做。

To check if you have the permission already, use 要检查您是否已经拥有权限,请使用

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_SMS);

To request permission, use 要请求许可,请使用

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