⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 discoverconnect.java

📁 蓝牙手机通信示例代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        }
    }

    // Innerclass
    /** The ClientThread is used to search for devices/Services and connect to them. <br>
     * A thread is needed otherwise it would not be possible to display
     * anything to the user.
     */
    private class ClientThread
    extends Thread
    {
        // Search type
        private int searchType;

        /** Constructor
         * @param st The search type. Possible values:
         * {@link BluetoothDiscovery.SEARCH_CONNECT_FIRST_FOUND SEARCH_CONNECT_FIRST_FOUND},
         * {@link BluetoothDiscovery.SEARCH_CONNECT_ALL_FOUND SEARCH_CONNECT_ALL_FOUND},
         * {@link BluetoothDiscovery.SEARCH_ALL_DEVICES_SELECT_ONE SEARCH_ALL_DEVICES_SELECT_ONE},
         * {@link BluetoothDiscovery.SEARCH_ALL_DEVICES_SELECT_SEVERAL SEARCH_ALL_DEVICES_SELECT_SEVERAL}.
         */
        protected ClientThread( int st )
        {
            // store search type
            searchType = st;
        }


        /**
         * This method runs the client.
         */
        public void run()
        {
            try
            {
                BluetoothConnection conn[] = disc.searchService( searchType );
                if( conn.length != 0 )
                {   // Create Canvas object which deals with receive and send
                    nc = new NumberCanvas( conn );
                    // Set as new display
                    display.setCurrent( nc );
                }
                else
                {   // nothing found
                    startUI();
                }
            }
            catch( Exception e )
            {    // display error message
                showAlertAndExit( "Error:", e.getMessage(), AlertType.ERROR );
                return;
            }
        }
    }


    /*
     * Displays own and received keystrokes. <br>
     * This class is called on client and server side after connection has
     * been established.
     * If user presses one of the number keys this is displayed to the user.
     * The keypress is sent as well as character to the remote device.
     * If a character is received from remote device it is also displayed
     * in the Canvas. <br>
     * So user can see what key he has pressed and as well which key the
     * remote user has pressed.
     */
    private class NumberCanvas
    extends Canvas
    implements CommandListener
    {
        private String local_char;   // char from local device (ie. keypress)
        private String[] remote_char;  // char that was received from remote device(s)
        private BluetoothConnection[] btConnections;

        /** Constructor
         * @param con A list with the connected Bluetooth devices. */
        private NumberCanvas( BluetoothConnection[] btConns )
        {
            // Store stream connection
            btConnections = btConns;
            // Initial displayed chars
            local_char = "Conn.";
            remote_char = new String[btConnections.length];
            // Start receive thread
            for( int i=0; i<btConnections.length; i++ )
            {   // loop through all connections
                remote_char[i] = "Conn.";
                ReceiveThread rt = new ReceiveThread( i );
                rt.start();
            }

            // Add cancel command
            addCommand( new Command( "Cancel", Command.CANCEL, 1 ) );
            setCommandListener( this );
        }

        /**
         * Only processes "Cancel": Disconnect and return to start screen.
         * @param c The command.
         * @param s The displayable object. */
        public void commandAction( Command c, Displayable s )
        {
            if( c.getCommandType() == Command.CANCEL )
            {
                // Close all connections
                close();
                // Start again
                startUI();
            }
        }

        /**
         * Closes all connections
         */
        private synchronized void close()
        {
            // Disconnect
            for( int i=0; i<btConnections.length; i++ )
            {   // loop through all connections
                btConnections[i].close();
            }
        }

        /**
         * Draws the locally and the remote received keystrokes.
         * @param g Graphics object for 2d drawings.
         */
        public void paint( Graphics g )
        {
            Font f;
            int y, h;

            // Clear screen
            g.setColor( 255, 255, 255 ); // White
            g.fillRect( 0, 0, getWidth(), getHeight() );

            // Draw local char
            g.setColor( 0, 0, 255 ); // Blue
            // Set bigger Font
            f = Font.getFont( Font.FACE_MONOSPACE, Font.STYLE_BOLD, Font.SIZE_MEDIUM );
            g.setFont(f);

            y = 0;
            h = 16;
            g.drawString( "Local:", 0, y, Graphics.TOP | Graphics.LEFT );
            y += h;
            g.drawString( btConnections[0].getLocalName(), 0, y, Graphics.TOP | Graphics.LEFT );
            g.drawString( local_char, getWidth(),y, Graphics.TOP | Graphics.RIGHT);
            y += h;
            // Draw remote char(s)
            g.setColor( 255, 0, 0 ); // Red
            // remote names
            g.drawString( "Remote:", 0, y, Graphics.TOP | Graphics.LEFT );
            y += h;
            for( int i=0; i<btConnections.length; i++ )
            {
                g.drawString( btConnections[i].getRemoteName(), 0, y, Graphics.TOP | Graphics.LEFT );
                g.drawString( remote_char[i], getWidth(), y, Graphics.TOP | Graphics.RIGHT );
                y += 16;
            }
        }

        /**
         * Handles the (local) key presses. <br>
         * Keycode is updated on local display and sent to remote device(s).
         * @param keyCode Key that was pressed.
         */
        public void keyPressed( int keyCode )
        {
            char c;

            switch( keyCode )
            {
                case KEY_NUM0:
                    c = '0';
                    break;
                case KEY_NUM1:
                    c = '1';
                    break;
                case KEY_NUM2:
                    c = '2';
                    break;
                case KEY_NUM3:
                    c = '3';
                    break;
                case KEY_NUM4:
                    c = '4';
                    break;
                case KEY_NUM5:
                    c = '5';
                    break;
                case KEY_NUM6:
                    c = '6';
                    break;
                case KEY_NUM7:
                    c = '7';
                    break;
                case KEY_NUM8:
                    c = '8';
                    break;
                case KEY_NUM9:
                    c = '9';
                    break;
                case KEY_STAR:
                    c = '*';
                    break;
                case KEY_POUND:
                    c = '#';
                    break;
                default:
                    // Any other key does nothing
                    return;
            }

            // Update display
            updateLocalChar( (new Character(c)).toString() );
            // Send character to all connected devices
            for( int i=0; i<btConnections.length; i++ )
            {
                try
                {
                    OutputStream os = btConnections[i].getOutputStream();
                    os.write( (int) c );
                    os.flush();
                }
                catch( IOException e )
                {   // If error, then close
                    btConnections[i].close();
                    // Check if all connections are closed
                    if( checkIfAllClosed() )
                    {   // all closed -> return
                        return;
                    }
                }
            }
        }

        /**
         * Checks if all connections are closed.
         * If so, jumps to main menu.
         * @return true if all connection are closed, otherwise false.
         */
        private boolean checkIfAllClosed()
        {
            // Check if all connections are closed
            boolean allclosed = true;
            for( int l=0; l<btConnections.length; l++ )
            {
                if( btConnections[l].isClosed() != true  )
                {   // still open
                    allclosed = false;
                }
            }
            // If all connections closed then restart
            if( allclosed )
            {   // And restart
                startUI();
            }
            // return
            return allclosed;
        }

        /**
         * Updates the local key that is displayed to user.
         * It also generates a repaint to the Canvas.
         * @param c String that is displayed to the user.
         */
        private void updateLocalChar( String c )
        {
            // Store char
            local_char = c;
            // Repaint
            repaint();
        }

        /**
         * Updates one of the remote keys that are displayed to user.
         * It also generates a repaint to the Canvas.
         * @param index Index to the remote device for which the string
         * should be updated.
         * @param c String that is displayed to the user.
         */
        private void updateRemoteChar( int index, String c )
        {
            // Store char
            remote_char[index] = c;
            // Repaint
            repaint();
        }

        // Inner class
        /**
         * The ReceiveThread is used to receive the remote keypresses. <br>
         * For each remote device there exists an own RecieveThread.
         */
        private class ReceiveThread
        extends Thread
        {
            int index;

            /**
             * Constructor.
             * @param i Index, that corresponds to the number of the BluetoothConnection.
             */
            public ReceiveThread( int i )
            {
                // Store
                index = i;
            }

            /**
             * Reads from stream until end of stream reached (disconnect).<br>
             * The read character (which is the key the remote user pressed) is
             * displayed to the local user.
             */
            public void run()
            {
                // Read input stream (data from remote device)
                int inp;

                while( true )
                {
                    // Read (blocking)
                    try
                    {
                        inp = btConnections[index].getInputStream().read();
                    }
                    catch( IOException e )
                    {    // If error, then disconnect
                        btConnections[index].close();
                        // Check if all connections are closed
                        checkIfAllClosed();
                        // show that device is disconnected
                        updateRemoteChar( index, "Disc." );
                        return;
                    }

                    if( inp == -1 )
                    {   // Close
                        btConnections[index].close();
                        // Check if all connections are closed
                        checkIfAllClosed();
                        // show that device is disconnected
                        updateRemoteChar( index, "Disc." );
                        return;
                    }
                    updateRemoteChar( index,  (new Character((char)inp)).toString() );
                }
            }
        }
    }

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -