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

📄 bluetooth.java

📁 蓝牙技术 本游戏来源于网络
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
            {
                block_c.notifyAll();
            }
            // Note: progressBar is anyway stopped by searchService method
        }

        /**
         * NextDeviceServiceSearch.
         * Retrieves the next device from the stored list and searches
         * for the Service on this device.
         */
        private void nextDeviceServiceSearch()
        {
            UUID[] u = new UUID[1];
            u[0] = new UUID( serviceUUID, false );
            int attrbs[] =
            { SERVICE_NAME_BASE_LANGUAGE }; // Retrieved service record should include service name
            RemoteDevice dev;

            // Update progress bar
//            ((PageProgressBar)progressBar).nextDevice();

            // Retrieve next device
            try
            {
                dev = (RemoteDevice) cached_devices.firstElement();
                cached_devices.removeElementAt( 0 );
            }
            catch( Exception e )
            {   // All devices searched
                if( foundServiceRecords.size() == 0 )
                {   // If no device found then alert to user
                    warning = "No service found!";
                }
                // If service not found on any device return to main,
                // also if SEARCH_CONNECT_ALL_FOUND was selected.
                if( (foundServiceRecords.size() == 0)
                | (searchType == SEARCH_CONNECT_ALL_FOUND) )
                {  // return to main function
                    synchronized( block_c )
                    {
                        block_c.notifyAll();
                    }
                }
                // If deviceList is used, then it's ready now (will change "Stop"
                // button into "Cancel".
                if( deviceList != null )
                {
                    deviceList.ready();
                }
                return;
            }

            // search for the service
            try
            {
                currServRec = null;
                serviceSearchTransId = discoveryAgent.searchServices( attrbs, u, dev, listener );
            }
            catch( BluetoothStateException e )
            {
                // an error occured
                // Try next device
                nextDeviceServiceSearch();
            }
        }

        /** Is called when the service we searched for is found.
         *
         * @param transID the transaction ID of the service search that is posting the result.
         * @param servRecord The service we searched for.
         */
        public void servicesDiscovered( int transID, ServiceRecord[] servRecord )
        {
            // A Service was found on the device.
            currServRec = servRecord[0];
        }

        /** Depending on the search type different actions are taken.
         * Possible search types are:<br>
         * {@link #SEARCH_CONNECT_FIRST_FOUND SEARCH_CONNECT_FIRST_FOUND},<br>
         * {@link #SEARCH_CONNECT_ALL_FOUND SEARCH_CONNECT_ALL_FOUND},<br>
         * {@link #SEARCH_ALL_DEVICES_SELECT_ONE SEARCH_ALL_DEVICES_SELECT_ONE}, and<br>
         * {@link #SEARCH_ALL_DEVICES_SELECT_SEVERAL SEARCH_ALL_DEVICES_SELECT_SEVERAL}.
         * See also {@link #searchService searchService}.
         * @param transID the transaction ID of the service search that is posting the result.
         * @param respCode a code showing how the service search was completed
         */
        public void serviceSearchCompleted( int transID, int respCode )
        {
            synchronized( block_ss )
            {
                // Reset trans action id
                serviceSearchTransId = -1;

                // Collect all devices with right service
                if( currServRec != null )
                {    // A device with this service is found, so add it
                    foundServiceRecords.addElement( currServRec );
                    urlStrings.addElement( currServRec.getConnectionURL( ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false ) );
                }

                switch( searchType )
                {
                    case SEARCH_CONNECT_FIRST_FOUND:
                        // Stop searching after first device with the service is found
                        if( currServRec != null )
                        {    // A device with this service is found, so stop
                            synchronized( block_c )
                            {
                                block_c.notifyAll();
                            }
                            return;
                        }
                        break;
                    case SEARCH_CONNECT_ALL_FOUND:
                        break;
                    case SEARCH_ALL_DEVICES_SELECT_ONE:
                    case SEARCH_ALL_DEVICES_SELECT_SEVERAL:
                        if( currServRec != null )
                        {   // Update displayed list
                            displayFoundServices();
                        }
                        break;
                }

                // Check if service search was terminated
                if( respCode == SERVICE_SEARCH_TERMINATED )
                {   // Notify the terminator (cancelServSearch)
                    synchronized( block_ss )
                    {
                        block_ss.notifyAll();
                    }
                }
                else
                {   // Search next device
                    nextDeviceServiceSearch();
                }
            }
        }

        /**
         * displayFoundServices
         * Updates the displayed found services.
         */
        private void displayFoundServices()
        {
            if( deviceList == null )
            {   // Create new device list
                int lt;

                if( searchType == SEARCH_ALL_DEVICES_SELECT_SEVERAL )
                {
                    lt = List.MULTIPLE;
                }
                else
                {
                    lt = List.IMPLICIT;
                }
                // Create new device lsit
                deviceList = new DeviceList( lt );
            }
            // Append new service/device
            // Retrieve remote name
            DataElement de = ((ServiceRecord)foundServiceRecords.lastElement()).getAttributeValue( SERVICE_NAME_BASE_LANGUAGE );
            String rname = (String) de.getValue();
            // Add device to list
            deviceList.append( rname, null );
        }
    }

    /**
     * DeviceList is a List to display the found devices.
     */

    private class DeviceList
    extends List
    implements CommandListener
    {
        // The possible commands
        private Command ok;
        private Command stop;
        private Command cancel;

        /** Constructor of DeviceList
         * @param list_type determines the type of list. Either MULTIPLE or IMPLICIT.
         */
        public DeviceList( int list_type )
        {
            super( "Select:", list_type );

            // Set text wrap around
            setFitPolicy( Choice.TEXT_WRAP_ON );

            // Create commands
            ok = new Command( "OK", Command.OK, 1 );
            stop = new Command( "Stop", Command.STOP, 1 );
            cancel = new Command( "Cancel", Command.CANCEL, 1 );
            // append commands
            addCommand( ok );
            addCommand( stop );
            setCommandListener( this );
//            Display display = Display.getDisplay( this );
//            display.setCurrent( this );
        }

        /**
         * Cancels the current service search.
         */
        private void cancelServSearch()
        {
            synchronized( block_ss )
            {
                if( serviceSearchTransId != -1 )
                {   // only if there is a service search active
                    discoveryAgent.cancelServiceSearch( serviceSearchTransId );
                    // wait until service search has terminated
                    try
                    {
                        block_ss.wait();
                    }
                    catch( InterruptedException e )
                    {
                        // we can ignore this
                    }
                }
            }
        }

        /**
         * Should be called when no more elements will be added to the
         * list.
         * The "Stop" button will change into "Cancel".
         */
        public void ready()
        {
            removeCommand( stop );
            addCommand( cancel );
        }

        /**
         * Respond to commands.
         * @param c The command.
         * @param s The displayable object. */
        public void commandAction( Command c, Displayable s )
        {
            int com = c.getCommandType();

            if( (c == SELECT_COMMAND) && (searchType == SEARCH_ALL_DEVICES_SELECT_ONE) )
            {                // Behave the same as if OK was pressed.
                com = Command.OK;
            }

            switch( com )
            {
                case Command.OK:
                    // User selected OK
                    // Cancel the current service search.
                    cancelServSearch();

                    // Remove all elements that are not selected
                    for( int i=size()-1; i>=0; i-- )
                    {
                        if( ! isSelected(i) )
                        {   // not selected then remove
                            urlStrings.removeElementAt(i);
                        }
                    }

                    // return to searchService function
                    synchronized( block_c )
                    {
                        block_c.notifyAll();
                    }
                    break;

                case Command.STOP:
                    // User stopped
                    // Cancel the current service search.
                    cancelServSearch();
                    // Exchange stop button with cancel button
                    ready();
                    break;

                case Command.CANCEL:
                    // User cancelled
                    // Remove all elements
                    urlStrings.removeAllElements();
                    // return to main function
                    synchronized( block_c )
                    {
                        block_c.notifyAll();
                    }
                    break;
            }
        }
    }
//#endif

    public synchronized void close()
    {
//#ifdef useBT
    	try
		{
	        // Disconnect
	        for( int i=0; i<btConnections.length; i++ )
	        {   // loop through all connections
	            btConnections[i].close();
	        }
		}
    	catch (Exception e)
		{

		}
    	finally
		{
    		recThread = false;
    		synchronized (block_r)
			{
    			block_r.notify();
			}
		}
//#endif
    }


//#ifdef useBT
    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()
        {

            while( recThread )
            {
                int inp;

                synchronized( block_r )
    			{
                	if (BlueTooth.bReadReady)
                	{
    	                // Read (blocking)
    	                try
    	                {
    	                		inp = btConnections[index].readInt();
    	                		BlueTooth.gotInt = inp;
    	                		BlueTooth.bReadReady = false;
//    //System.out.println("*** THE THREAD " + inp);
    	                }
    	                catch( IOException e )
    	                {    // If error, then disconnect
    	                    btConnections[index].close();
    	                    BlueTooth.ConnectCancelled = true;
                    		BlueTooth.bReadReady = false;
//    //System.out.println("*** THE THREAD BOMBED1");
    	                    return;
    	                }

    	                if( inp == -1 )
    	                {   // Close
    	                    btConnections[index].close();
    	                    BlueTooth.ConnectCancelled = true;
                    		BlueTooth.bReadReady = false;
    	                    // Check if all connections are closed
//    //System.out.println("*** THE THREAD BOMBED2");
    	                    return;
    	                }
                	}
                	try
					{
                		block_r.wait();
					}
                	catch (InterruptedException e)
					{
//                		e.printStackTrace();
					}
    			}
            }
        }
    }

//#endif
}

⌨️ 快捷键说明

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