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

📄 discoverconnect.java

📁 蓝牙手机通信示例代码
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
// Copyright 2004 Nokia Corporation.
//
// THIS SOURCE CODE IS PROVIDED 'AS IS', WITH NO WARRANTIES WHATSOEVER,
// EXPRESS OR IMPLIED, INCLUDING ANY WARRANTY OF MERCHANTABILITY, FITNESS
// FOR ANY PARTICULAR PURPOSE, OR ARISING FROM A COURSE OF DEALING, USAGE
// OR TRADE PRACTICE, RELATING TO THE SOURCE CODE OR ANY WARRANTY OTHERWISE
// ARISING OUT OF ANY PROPOSAL, SPECIFICATION, OR SAMPLE AND WITH NO
// OBLIGATION OF NOKIA TO PROVIDE THE LICENSEE WITH ANY MAINTENANCE OR
// SUPPORT. FURTHERMORE, NOKIA MAKES NO WARRANTY THAT EXERCISE OF THE
// RIGHTS GRANTED HEREUNDER DOES NOT INFRINGE OR MAY NOT CAUSE INFRINGEMENT
// OF ANY PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OWNED OR CONTROLLED
// BY THIRD PARTIES
//
// Furthermore, information provided in this source code is preliminary,
// and may be changed substantially prior to final release. Nokia Corporation
// retains the right to make changes to this source code at
// any time, without notice. This source code is provided for informational
// purposes only.
//
// Nokia and Nokia Connecting People are registered trademarks of Nokia
// Corporation.
// Java and all Java-based marks are trademarks or registered trademarks of
// Sun Microsystems, Inc.
// Other product and company names mentioned herein may be trademarks or
// trade names of their respective owners.
//
// A non-exclusive, non-transferable, worldwide, limited license is hereby
// granted to the Licensee to download, print, reproduce and modify the
// source code. The licensee has the right to market, sell, distribute and
// make available the source code in original or modified form only when
// incorporated into the programs developed by the Licensee. No other
// license, express or implied, by estoppel or otherwise, to any other
// intellectual property rights is granted herein.



//==============================================================================
// Package Statements



//==============================================================================
// Import Statements

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import java.io.*;
import javax.bluetooth.*;


//==============================================================================
// CLASS (OR INTERFACE) DECLARATIONS

/** The <code>DiscoverConnect</code> is an example that shows how to use device 
 *  and service discovery.
 *  After device with service has been found a connection is set up
 *  to that device.
 *
 *  Every keystroke is then transmitted to the other device and displayed there
 *  until connection is disconnected.
 *  <br>
 *  After starting the MIDlet you can choose your role: server or client.<br>
 *
 * The server waits that someone connects. After selecting "Server" you have to accept the user confirmation.
 * The device will then wait on a connection:<br>
 * <img src="doc-files/crop_server_select.jpg">
 *
 * <img src="doc-files/crop_server_selected_1_acceptance.jpg">
 *
 * <img src="doc-files/crop_server_selected_2_waiting.jpg"><br>
 *
 * When remote device has connected you see screen below and as soon as you press the number keys
 * (on local and remote device) they are shown on the screen (in this example user at remote device
 * pressed "1" and user on local device pressed "6"):<br>
 * <img src="doc-files/crop_server_conn_ptp_1.jpg">
 * <img src="doc-files/crop_server_conn_ptp_2.jpg"><br>
 *
 * <P>
 * When selecting to be a client you have 4 choices which are different in the way the selection of the
 * device(s) to connect to is done.<br>
 * <P>
 *
 * A) Connect to the device which is the <b>first found</b> device which matches the service:<br>
 * <img src="doc-files/crop_client_first_found_select.jpg"><br>
 * You will see an intermediate "searching" display until remote device is connected:<br>
 * <img src="doc-files/crop_client_conn_ptp_1.jpg">
 * <img src="doc-files/crop_client_conn_ptp_2.jpg"><br>
 * <P>
 *
 * B)  Connect to all devices which match the searched service:<br>
 * <img src="doc-files/crop_client_all_found_select.jpg"><br>
 * You will see an intermediate "searching" display until remote devices are connected:<br>
 * <img src="doc-files/crop_client_conn_ptp_1.jpg">
 * <img src="doc-files/crop_client_conn_ptp_2.jpg"><br>
 * <P>
 *
 * C) Display all found devices with a matching service and allow user to select <b>one</b> of these devices:<br>
 * <img src="doc-files/crop_client_sel_one_select.jpg"><br>
 * Select the device<br>
 * <img src="doc-files/crop_client_sel_one_selected.jpg"><br>
 * which then will be connected:<br>
 * <img src="doc-files/crop_client_conn_ptp_1.jpg">
 * <img src="doc-files/crop_client_conn_ptp_2.jpg"><br>
 * <P>
 *
 * D) Display all found devices with a matching service and allow user to select <b>several</b> of these devices:<br>
 * <img src="doc-files/crop_client_sel_several_select.jpg"><br>
 * The devices are displayed:<br>
 * <img src="doc-files/crop_client_sel_several_selected_1.jpg"><br>
 * Select the devices<br>
 * <img src="doc-files/crop_client_sel_several_selected_2.jpg"><br>
 * which then will be connected:<br>
 * <img src="doc-files/crop_client_conn_ptmp_1.jpg"><br>
 *
 */

public class DiscoverConnect
    extends MIDlet
    implements CommandListener
{
    //==============================================================================
    // Final variables (Class constants)

    //==============================================================================
    // Class (static) variables

    //==============================================================================
    // Instance variables
    private Display display;
    private BluetoothDiscovery disc;
    private NumberCanvas nc = null;

    //==============================================================================
    // Constructors and miscellaneous (finalize method, initialization block,...)

    /**
     * Creates a <code>DiscoverConnect</code> object.
     */
    public DiscoverConnect()
    {
        display = Display.getDisplay( this );
        ErrorScreen.init(null, display);

        // Create Discovery Object
        disc = new BluetoothDiscovery( display );
    }

    /** Called when MIDlet is started.
     */
    public void startApp()
    {
        String name;

        // Set UUID
        disc.setServiceUUID( "20000000000010008000006057028C19" );

        // Check if Bluetooth is turned on
        try
        {
            name = LocalDevice.getLocalDevice().getFriendlyName();
        }
        catch( BluetoothStateException e )
        {   // display user notification
            showAlertAndExit( "", "Please switch Bluetooth on!", AlertType.ERROR );
            return;
        }

        // Sets the name how this device is shown to the remote user
        disc.setName( name );

        // Start the UI
        startUI();
    }

    /** Offers the user a selection: Client or Server
     */
    private void startUI()
    {
        // Create new screen object for selecting the role: client or server
        ClientServerSelect select = new ClientServerSelect();

        display.setCurrent( select );
   }

    /**
     * Pause is a no-op since there are no background activities or
     * record stores that need to be closed.
     */
    public void pauseApp()
    {
    }

    /**
     * Destroy should cleanup everything.
     * In the case here there is nothing to cleanup.
     * @param unconditional not used
     */
    public void destroyApp( boolean unconditional )
    {
    }

    /**
     * Displays the string that is passed. Waits for user confirmation
     * and offers possibility to exist the Midlet. Used to show notifications to the user.
     * @param t title string that is displayed to the user.
     * @param s string that is displayed to the user.
     * @param type AlertType: ALARM, CONFIRMATION, ERROR, INFO, WARNING
     */
    private void showAlertAndExit( String t, String s, AlertType type )
    {
        Alert a = new Alert( t, s, null, type );
        a.addCommand( new Command( "Exit", Command.EXIT, 1 ) );
        a.setCommandListener( this );
        display.setCurrent( a );
    }


    /** Terminate Midlet.
     */
    public void Exit()
    {
        destroyApp( false );
        notifyDestroyed();
    }

    /** Respond to commands, including exit.
     * On the exit command, cleanup and notify that the MIDlet has been destroyed.
     * @param c The command.
     * @param s The displayable object. */
    public void commandAction(Command c, Displayable s)
    {
        switch( c.getCommandType() )
        {
            case Command.EXIT:
                // User chose to quit the application
                Exit();
                break;
        }
    }


    // Inner class
    /** UI to select client or server role.
     * User can choose between 4 different behaviours of the client, which mainly
     * with the way the found devices are presented to the user.
     * The 4 different possibilities directly map to search type parameter of
     * method {@link BluetoothDiscovery#searchService BluetoothDiscovery.searchService}: <br>
     * {@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}.
     */
    public class ClientServerSelect
    extends List
    implements CommandListener
    {
        /**
         * Constructor
         */
        public ClientServerSelect()
        {
            super( "Select Role:", List.IMPLICIT );

            // Set text wrap around
            setFitPolicy( Choice.TEXT_WRAP_ON );
            // Create List
            append( "Server", null );
            append( "Client (FIRST_FOUND)", null );
            append( "Client (ALL_FOUND)", null );
            append( "Client (SELECT_ONE)", null );
            append( "Client (SELECT_SEVERAL)", null );
            // append commands
            addCommand( new Command( "Select", Command.OK, 1 ) );
            addCommand( new Command( "Quit", Command.EXIT, 1 ) );
            setCommandListener( this );
        }

        /** Starts server or client (or cancels/terminate the midlet).
         * @param c The command.
         * @param d The displayable object. */
        public void commandAction( Command c, Displayable d )
        {
            if( c.equals(List.SELECT_COMMAND) || (c.getCommandType() == Command.OK) )
            {
                int i = getSelectedIndex();
                String s = getString( i );
                if( s.equals( "Server" ) )
                {
                    // Start Server
                    ServerThread st = new ServerThread();
                    st.start();
                }
                if( s.equals( "Client (FIRST_FOUND)" ) )
                {   // Start Client with SEARCH_CONNECT_FIRST_FOUND
                    ClientThread ct = new ClientThread( disc.SEARCH_CONNECT_FIRST_FOUND );
                    ct.start();
                }
                if( s.equals( "Client (ALL_FOUND)" ) )
                {   // Start Client with SEARCH_CONNECT_ALL_FOUND
                    ClientThread ct = new ClientThread( disc.SEARCH_CONNECT_ALL_FOUND );
                    ct.start();
                }
                if( s.equals( "Client (SELECT_ONE)" ) )
                {   // Start Client with SEARCH_ALL_DEVICES_SELECT_ONE
                    ClientThread ct = new ClientThread( disc.SEARCH_ALL_DEVICES_SELECT_ONE );
                    ct.start();
                }
                if( s.equals( "Client (SELECT_SEVERAL)" ) )
                {   // Start Client with SEARCH_ALL_DEVICES_SELECT_SEVERAL
                    ClientThread ct = new ClientThread( disc.SEARCH_ALL_DEVICES_SELECT_SEVERAL );
                    ct.start();
                }
            }
            else if( c.getCommandType() == Command.EXIT )
            {
                // pass through to midlet
                Exit();
            }
        }
    }


    // Innerclass
    /** The ServerThread is used to wait until someone connects. <br
     * A thread is needed otherwise it would not be possible to display
     * anything to the user.
     */
    private class ServerThread
    extends Thread
    {
        /**
         * This method runs the server.
         */
        public void run()
        {
            try
            {
                // Wait on client
                BluetoothConnection[] con = disc.waitOnConnection();
                if( con[0] == null )
                {   // Connection cancelled
                    startUI();
                    return;
                }

                // Create Canvas to display keystrokes
                nc = new NumberCanvas( con );

                // Set as new display
                display.setCurrent( nc );
            }
            catch( Exception e )
            {    // display error message
                showAlertAndExit( "Error:", e.getMessage(), AlertType.ERROR );
                return;
            }

⌨️ 快捷键说明

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