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

📄 servicediscoverylist.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 example.btl2capecho;


import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;

import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DataElement;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import example.btl2capecho.MIDletApplication;


class ServiceDiscoveryList
    extends List
    implements CommandListener,
               DiscoveryListener,
               Runnable
{
    private final static String TITLE = "New search";
    private final static int WAIT_MILLIS = 500; // milliseconds
    private final static String[] ACTIVITY = { "",
                                               ".",
                                               "..",
                                               "...",
                                               "...." };

    private final UUID uuid;
    private final MIDletApplication midlet;
    private final Command backCommand;
    private final Command searchCommand;
    private final Command openCommand;
    private final Command stopCommand;
    private final Command logCommand;
    private final Command exitCommand;

    private final int sdTransMax;
    private final int inquiryAccessCode;

    private DiscoveryAgent discoveryAgent;
    private volatile boolean inquiryInProgress = false;
    private volatile int numServiceSearchesInProgress = 0;
    private volatile boolean aborting = false;
    private volatile Thread thread;
    private Displayable backDisplayable;

    private Vector unsearchedRemoteDevices = new Vector();
    private Vector transIds = new Vector();
    private Hashtable matchingServiceRecords = new Hashtable();

    private int numConnectionsAlreadyOpen = 0;


    ServiceDiscoveryList(MIDletApplication midlet,
                         String uuidString,
                         int inquiryAccessCode)
    {
        super(TITLE, List.IMPLICIT);
        this.midlet = midlet;
        uuid = new UUID(uuidString, false);
        this.inquiryAccessCode = inquiryAccessCode;

        openCommand = new Command("Open connection",
                                  Command.SCREEN,
                                  1);
        searchCommand = new Command("Search", Command.SCREEN, 2);
        logCommand = new Command("View log", Command.SCREEN, 3);
        stopCommand = new Command("Stop", Command.SCREEN, 4);
        backCommand = new Command("Back", Command.BACK, 5);
        exitCommand = new Command("Exit", Command.EXIT, 0);


        String property =
               LocalDevice.getProperty("bluetooth.sd.trans.max");
        sdTransMax = Integer.parseInt(property);

        // create discovery agent
        try
        {
            discoveryAgent =
                LocalDevice.getLocalDevice().getDiscoveryAgent();

            addCommand(logCommand);
            addCommand(exitCommand);
            addCommand(searchCommand);
            setCommandListener(this);

            start();
        }
        catch(BluetoothStateException e)
        {
            midlet.serviceDiscoveryListFatalError(
                       "Couldn't get a discovery agent: '" +
                       e.getMessage() + "'");
        }
    }


    public void addBackCommand(Displayable backDisplayable)
    {
        this.backDisplayable = backDisplayable;
        removeCommand(backCommand);
        addCommand(backCommand);
    }


    public synchronized void start()
    {
        thread = new Thread(this);
        thread.start();
    }


    public synchronized void abort()
    {
        thread = null;
    }


    public void init(int numConnectionsAlreadyOpen)
    {
        this.numConnectionsAlreadyOpen =
             numConnectionsAlreadyOpen;

        // stop any pending searches
        if (inquiryInProgress ||
            numServiceSearchesInProgress > 0)
        {
            cancelPendingSearches();
        }

        // remove any old list elements
        while (size() > 0)
        {
            delete(0);
        }
    }


    private synchronized void setInquiryInProgress(boolean bool)
    {
        inquiryInProgress = bool;
    }


    public void commandAction(Command command, Displayable d)
    {
        if (command == logCommand)
        {
            midlet.serviceDiscoveryListViewLog(this);
        }
        else if (command == searchCommand &&
                 !inquiryInProgress &&
                 (numServiceSearchesInProgress == 0))
        {
            // new inquiry started

            removeCommand(openCommand);

            // remove old device lists
            unsearchedRemoteDevices.removeAllElements();
            for (Enumeration keys = matchingServiceRecords.keys();
                 keys.hasMoreElements();)
            {
                matchingServiceRecords.remove(keys.nextElement());
            }

            // delete all old List items
            while (size() > 0)
            {
                delete(0);
            }

            try
            {
                // disable page scan and inquiry scan
                LocalDevice dev = LocalDevice.getLocalDevice();
                dev.setDiscoverable(DiscoveryAgent.NOT_DISCOVERABLE);

                String iacString =
                           LogScreen.inquiryAccessCodeString(inquiryAccessCode);
                LogScreen.log("startInquiry (" +
                              iacString + ")\n");

                // this is non-blocking
                discoveryAgent.startInquiry(inquiryAccessCode, this);

                setInquiryInProgress(true);
                addCommand(stopCommand);
                removeCommand(searchCommand);
            }
            catch (BluetoothStateException e)
            {
                addCommand(searchCommand);
                removeCommand(stopCommand);
                midlet.serviceDiscoveryListError(
                           "Error during startInquiry: '" +
                           e.getMessage() + "'");
            }
        }
        else if (command == stopCommand)
        {
            // stop searching
            if (cancelPendingSearches())
            {
                setInquiryInProgress(false);
                removeCommand(stopCommand);
                addCommand(searchCommand);
            }
        }
        else if (command == exitCommand)
        {
            midlet.serviceDiscoveryListExitRequest();
        }
        else if (command == openCommand)
        {
            int size = this.size();
            boolean[] flags = new boolean[size];
            getSelectedFlags(flags);
            Vector selectedServiceRecords = new Vector();
            for (int i=0; i < size; i++)
            {
                if (flags[i])
                {
                    String key = getString(i);
                    ServiceRecord rec =
                        (ServiceRecord) matchingServiceRecords.get(key);
                    selectedServiceRecords.addElement(rec);
                }
            }

            // try to perform an open on selected items
            if (selectedServiceRecords.size() > 0)
            {
                String value = LocalDevice.getProperty(
                                   "bluetooth.connected.devices.max");
                int maxNum = Integer.parseInt(value);

                int total = numConnectionsAlreadyOpen +
                            selectedServiceRecords.size();
                if (total > maxNum)
                {
                    midlet.serviceDiscoveryListError(
                               "Too many selected. " +
                               "This device can connect to at most " +
                               maxNum + " other devices");
                }
                else
                {
                    midlet.serviceDiscoveryListOpen(
                               selectedServiceRecords);
                }
            }
            else
            {
                midlet.serviceDiscoveryListError(
                          "Select at least one to open");
            }
        }
        else if (command == backCommand)
        {
            midlet.serviceDiscoveryListBackRequest(backDisplayable);
        }
    }

⌨️ 快捷键说明

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