BlueTooth

28472 단어

BlueTooth

  • 권한 추가:
  • 블루투스를 켜고 검색할 수 있도록 설정합니다
  • 블루투스를 켜세요
  • 블루투스 끄기
  • 블루투스 스캐닝
  • 클릭하여 연결합니다
  • 블루투스가 페어링되어 있음을 표시합니다
  • 페어링된 블루투스 장치에 메시지를 보냅니다
  • 서버를 열어 장치 메시지를 수신합니다

  • 권한 추가:

       <!--   -->
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <!--  GPS  -->
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    

    Bluetooth를 열고 검색할 수 있도록 설정

     // -> 
    	Intent intent = new Intent();
    	intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);// 
        intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);// 
       intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);// 200s 
        startActivityForResult(intent,100);
    

    블루투스 켜기

    Intent intent = new Intent();
                    intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                    intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
                    startActivity(intent);
    

    Bluetooth 끄기


    Bluetooth 관리 및 적합성 확보
    BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();
    
    bluetoothAdapter.disable();// 
    

    블루투스 스캔


    브로드캐스트를 통한 브로드캐스트 수신
     class MyRecevier extends BroadcastReceiver{
    
            @Override
            public void onReceive(Context context, Intent intent) {
                if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
                    BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    ss.add(bluetoothDevice);
                    blueToothAdapter1.notifyDataSetChanged();
                }
            }
        }
    

    클릭하여 연결

    lvConnectable.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BluetoothDevice device = ss.get(position);
                    device.createBond();
                }
            });
    

    1. 방송 등록
    myRecevier=new MyRecevier();
            IntentFilter intentFilter = new IntentFilter();// 
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            registerReceiver(myRecevier,intentFilter);
    
    bluetoothAdapter.startDiscovery();
    

    페어링된 Bluetooth 표시

    Set<BluetoothDevice> bondedDevicess = bluetoothAdapter.getBondedDevices();
                    bondedDevices.removeAll(bondedDevices);
                    bondedDevices.addAll(bondedDevicess);
                    blueToothAdapter.notifyDataSetChanged();
    

    페어링된 Bluetooth 장치에 메시지 보내기


    클라이언트 열기
    public class BlueToothSocket extends Thread{
        private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
    
        BluetoothDevice device;
        String message;
    
        public BlueToothSocket(BluetoothDevice device, String message) {
            this.device = device;
            this.message = message;
        }
    
        @Override
        public void run() {
            try {
                BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid);
                socket.connect();
                if(socket.isConnected()){
                    socket.getOutputStream().write(message.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    }
    
    lvConnected.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    BluetoothDevice device = bondedDevices.get(position);
                    new BlueToothSocket(device,"123").start();
                }
            });
    

    서버 켜기 페어링된 장치 메시지 수신

    public class BlueToothSeverSocket extends Thread{
        private BluetoothSocket socket;
        private Handler handler;
    
        public BlueToothSeverSocket(BluetoothSocket socket, Handler handler) {
            this.socket = socket;
            this.handler = handler;
        }
    
        @Override
        public void run() {
            StringBuffer buffer = new StringBuffer();
            try {
                InputStream is = socket.getInputStream();
                int len = 0;
                byte[] b = new byte[1024];
                int read = is.read(b);
                String s = new String(b, 0, read);
                Log.i("111", "run: ");
    
                Message message = new Message();
                message.what = 100;
                message.obj = s;
                Log.i("123", "run: "+s);
                handler.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    

    블루투스를 켤 때 라인을 켜기
    new Thread(){
                        @Override
                        public void run() {
                            while (true){
                                try {
                                    BluetoothServerSocket socket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(bluetoothAdapter.getName(), uuid);
                                    while (true){
                                        BluetoothSocket accept = socket.accept();
                                        new BlueToothSeverSocket(accept,handler).start();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }.start();
    

    좋은 웹페이지 즐겨찾기