通过蓝牙在设备之间交换字符串

时间:2021-03-10 16:58:18

标签: android android-studio bluetooth unique-key

<块引用>

我是初学者,正在 android studio 上制作我的第一个项目。我想通过蓝牙在设备之间交换一个唯一的字符串,而无需在设备靠近时进行配对。以下是我尝试过但没有用的代码。我提到的代码是扫描部分只有当点击扫描它搜索设备并交换密钥但它不起作用。


     @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
                ON = (Button) findViewById(R.id.button3);
                OFF = (Button) findViewById(R.id.button5);
                Scan = (Button) findViewById(R.id.search);
                myBT = BluetoothAdapter.getDefaultAdapter();
                Interaction = (Button) findViewById(R.id.intr);
                intentON = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                other = (TextView)findViewById(R.id.textView4);
                bluelist = (ListView) findViewById(R.id.btList);
                //IntView = (ListView) findViewById(R.id.InList);
                arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
                pAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
                bluelist.setAdapter(arrayAdapter);
        
                random = UUID.randomUUID();
                getUUID = random.toString();
                code = (TextView) findViewById(R.id.textView6);
                data = getIntent().getExtras().getString("SomeNumbers");
                code.setText(data);
                send = (String) code.getText();
        
                checkPermission();
        
                ON.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
        
                        if(myBT.isEnabled())
                            Toast.makeText(getApplicationContext(), "Bluetooth already Enabled", Toast.LENGTH_SHORT).show();
                        else
                            bluetoothOn();
                    }
                });
        
                OFF.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bluetoothOff();
                    }
                });
        
                Scan.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        discover();
                    }
                });
                bluelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //pairDevice(device);
                    }
                });
                Interaction.setOnClickListener(new View.OnClickListener() {
        
                    @Override
                    public void onClick(View v) {
                        Intent getInteractions = new Intent(MainActivity.this, Interactions.class);
                        //Bundle args = new Bundle();
                        //args.putSerializable("Exposure", (Serializable)arrayList);
                        getInteractions.putStringArrayListExtra("Exposure", arrayList);
                        startActivity(getInteractions);
                    }
                });
            }
        
            @Override
            protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                if (requestCode == BLUETOOTH_REQ_CODE) {
                    if (resultCode == RESULT_OK) {
                        Toast.makeText(getApplicationContext(), "Bluetooth is Enabled", Toast.LENGTH_LONG).show();
                    } else if (resultCode == RESULT_CANCELED) {
                        Toast.makeText(getApplicationContext(), "Bluetooth Disabled", Toast.LENGTH_LONG).show();
                    }
                }
            }
        
            private void discover(){
                if(myBT.isDiscovering()){
                    myBT.cancelDiscovery();
                    Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
                }
                else{
                    if(myBT.isEnabled()) {
                        arrayAdapter.clear(); // clear items
                        myBT.startDiscovery();
                        Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
                        registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        
                    }
                    else{
                        bluetoothOn();
                    }
                }
            }
        
            private final BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if(BluetoothDevice.ACTION_FOUND.equals(action)){
                        device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        // add the name to the list
                        arrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        arrayAdapter.notifyDataSetChanged();
                        ServerClass serverClass = new ServerClass();
                        serverClass.start();
                        ClientClass clientClass = new ClientClass(pairing);
                        clientClass.start();
                        sendReceive.write(send.getBytes());
                    }
                }
            };
Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case STATE_LISTENING:
                    Toast.makeText(getApplicationContext(), "Listening", Toast.LENGTH_SHORT).show();
                    break;
                case STATE_CONNECTING:
                    Toast.makeText(getApplicationContext(), "Connecting", Toast.LENGTH_SHORT).show();
                    break;
                case STATE_CONNECTED:
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                    break;
                case STATE_CONNECTION_FAILED:
                    Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
                    break;
                case STATE_MESSAGE_RECEIVED:
                    byte[] readBuff = (byte[]) msg.obj ;
                    String tempMsg = new String(readBuff,0,msg.arg1);
                    other.setText(tempMsg);
                    break;
            }
            return false;
        }
    });


    private class ServerClass extends Thread
    {
        private BluetoothServerSocket serverSocket;

        public ServerClass()
        {
            try {
                serverSocket = myBT.listenUsingInsecureRfcommWithServiceRecord(App_Name,random);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void run()
        {
            BluetoothSocket socket=null;
            while(socket == null)
            {
                try {
                    //Message msg = Message.obtain();
                    //msg.what=
                    //handler.sendMessage(msg);

                    socket=serverSocket.accept();
                } catch (IOException e) {
                    e.printStackTrace();
                    //Message msg = Message.obtain();
                    //msg.what=
                    //handler.sendMessage(msg);

                }
                if(socket != null)
                {
                    //Message msg = Message.obtain();
                    //msg.what=
                    //handler.sendMessage(msg);

                    sendReceive = new SendReceive(socket);
                    sendReceive.start();
                    break;

                }
            }
        }
    }

    private class ClientClass extends Thread
    {
        private BluetoothDevice device;
        private BluetoothSocket socket;

        public ClientClass(BluetoothDevice device1)
        {
            device=device1;
            try {
                socket = device.createRfcommSocketToServiceRecord(random);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void run()
        {
            try {
                socket.connect();
                sendReceive = new SendReceive(socket);
                sendReceive.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private class SendReceive extends Thread
    {
        private final BluetoothSocket bluetoothSocket;
        private final InputStream inputStream;
        private final OutputStream outputStream;

        public SendReceive(BluetoothSocket socket)
        {
            bluetoothSocket=socket;
            InputStream tempIn = null;
            OutputStream tempOut = null;

            try {
                tempIn = bluetoothSocket.getInputStream();
                tempOut = bluetoothSocket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream = tempIn;
            outputStream = tempOut;
        }
        public void run()
        {
            byte[] buffer = new byte[1024];
            int bytes;

            while(true)
            {
                try {
                    bytes = inputStream.read(buffer);
                    handler.obtainMessage(STATE_MESSAGE_RECEIVED,bytes,-1,buffer).sendToTarget();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void write(byte[] bytes)
        {
            try {
                outputStream.write(bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



0 个答案:

没有答案