簡體   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