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

📄 btutil.java

📁 A bluetooth SMS patcher Java ME application I made quickly after I thought about making one. What i
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
     */    public void cleanUp() {        localDevice = null;        agent = null;    }    /**     * The simplest way to discovery remote devices. This method will     * hang the execution until the device discovery process is finished.     * If you don't want the execution to be hanged, use discoverDevicesAsync()     * istead.     *     * TODO Optimize it!     *     * @return Vector A vector containing a list o RemoteDevice founds.     */    public Vector discoverDevicesSync() throws BtUtilException {        deviceDiscoveryFinished = false;        discoverDevicesAsync();        //Wait util the inquiry is finished. Remember that this method        //is synchronous.        synchronized (remoteDevices) {            while(!deviceDiscoveryFinished) {                try {                    out.println("[BtUtil API] Waiting for the device discovery end...");                    remoteDevices.wait();                } catch (InterruptedException ex) {                    ex.printStackTrace();                }            }        }        return remoteDevices;    }    /**     * Another way to discovery remote devices. In contrast to the     * discoverDevicesSync method, this method will not block the thread     * execution until all devices where found. It will just start the process     * and, as devices are found, the BtUtilClientListeners, registered with     * the addBtUtilClientListener method, will be notified.     */    public void discoverDevicesAsync() throws BtUtilException {        //Clear the discovered devices list.        if (remoteDevices == null) {            remoteDevices = new Vector();        } else {            remoteDevices.removeAllElements();        }        try {            out.println("[BtUtil API] Starting inquiry...");            boolean result = agent.startInquiry( DiscoveryAgent.GIAC, new Listener() );            out.println("[BtUtil API] Inquiry started. Waiting for responses...");        } catch ( BluetoothStateException e ) {            String msg = "[BtUtil API] Error when inquiring for remote devices: " + e.toString();            out.println(msg);            throw new BtUtilException(msg);        }    }    /**     * Do almost the same as the discoverDevicesSync method. The difference is     * because it doesn't trust on Bluetooth information.<p/>     *     * It means, sometimes, after a device inquiry, the Bluetooth implementation     * say no device was found, but it's not really true, because you know     * there's a bluetooth enable device in the neighborhood. So, to avoid these     * scenarios, in case of no device discovered, others tries will be executed.     *     * @param tries Number of tries before giving up a no device discovering.     * @param listener An object that will be notified each time a new try     * is started. If you don't want to receive these notifications, let it null.     *     * @return Vector A vector containing a list o RemoteDevice founds.     */    public Vector discoverDevicesSync(int tries, BtUtilClientListener listener) throws BtUtilException {        out.println("[BtUtil API] Going to try " + tries + " times to find remote devices.");        Vector devices = null;        int counter = 1;        boolean found = false;        while(!found && counter <= tries ) {//            resetBluetoothStack();//            initBluetoothStack();            //Notify listener the try #counter is about to start.            if (listener != null) {listener.tryingAgain(counter);}            out.println("[BtUtil API] Trying #" + counter + " to discover remote devices...");            devices = discoverDevicesSync();            out.println("[BtUtil API] Device discovery #" + counter + " finished. " + devices.size() + " devices found.");            if (devices != null && devices.size() > 0) {                found = true;            }            counter++;        }        out.println("[BtUtil API] Device discovery finished in " + (counter - 1) + " tries.");        return devices;    }    /**     * The simplest way to get a list of services available in a remote device.     * This method will hang the execution until the service discovery process     * is finished. If you don't want the execution to be hanged,     * use discoverServicesAsync() istead. Search only for RFCOMM services.     *     * @param RemoteDevice The device whose services should be discovered.     * @return Vector A list of ServiceRecord objects.     */    public Vector discoverServicesSync(RemoteDevice device) throws BtUtilException {        //Search only for RFCOMM services.        return discoverServicesSync(device, new String[] {"0003"});    }    /**     * The simplest way to get a list of services available in a remote device.     * This method will hang the execution until the service discovery process     * is finished. If you don't want the execution to be hanged,     * use discoverServicesAsync() istead.     *     * @param RemoteDevice The device whose services should be discovered.     * @param String[] The service classes UUIDs whose services will be searched for.     *                 Should be an hexa number, without the 0x prefix.     *                 For example: ABCD instead of 0xABCD     * @return Vector A list of ServiceRecord objects.     */    public Vector discoverServicesSync(RemoteDevice device, String[] serviceClassesUUIDs) throws BtUtilException {        serviceDiscoveryFinished = false;        discoverServicesAsync(device, serviceClassesUUIDs);        //Wait util the service discovery is finished.        //Remember that this method is synchronous.        synchronized (remoteServices) {            while(!serviceDiscoveryFinished) {                try {                    out.println("[BtUtil API] Waiting for the service discovery end...");                    //TODO [ALE] The following line blocks the                    remoteServices.wait();                } catch (Exception ex) {                    out.println("[BtUtil API] Waiting for the service discovery end failed. " + ex);                }            }        }        return remoteServices;    }    /**     * Another way to get the service list from a remote device.     * In contrast to dicoverServicesSync, this method is asyncrhonous, I mean,     * it doesn't block the thread execution. On the other hand, you must     * implement the BtUtilClientListener interface, so you can receive notes about how     * is going the requested service search.     *     * @param RemoteDevice The device whose services should be discovered.     * @param String[] The service class UUID whose services will be searched for.     *                 Should be an hexa number, without the 0x prefix.     *                 For example: ABCD instead of 0xABCD     */    public void discoverServicesAsync(RemoteDevice device, String[] serviceClassesUUIDs)    throws BtUtilException {        //Clean services found before.        remoteServices.removeAllElements();        //Get device's friendly name        String deviceFriendlyName = null;        try {            deviceFriendlyName = device.getFriendlyName(true);        } catch (IOException e) {            throw new BtUtilException("Failed to get device friendly name. " + e);        }        out.println(                "[BtUtil API] Starting asynchronous service discovery at device " +                "[" + deviceFriendlyName + "]");        //Where are going to try to discovery services of any        //class specifyied in serviceClassesUUIDs        //Will be used for the service search        UUID uuidSet[] = new UUID[serviceClassesUUIDs.length];        out.print("[BtUtil API] The service classes UUIDs to be searched are: ");        for (int i = 0; i < serviceClassesUUIDs.length; i++) {            out.print(" 0x" + serviceClassesUUIDs[i]);            uuidSet[i] = new UUID(serviceClassesUUIDs[i], false);        }        out.println(".");        //Id of the searching process.        int transId = 0;        try {            out.println("[BtUtil API] Initializing search for services...");            transId = agent.searchServices(null, uuidSet, device, new Listener());            out.println("[BtUtil API] Service discovery process started. Waiting for responses...");        } catch (Exception e) {            String msg = "Error when initializing service discovery. " + e;            out.println(msg);            agent.cancelServiceSearch(transId);        }    }    /**     * Get a Connection from the specified bluetooth service.     *     * @param btDeviceAddress The bluetooth device address where the service     *                        is running. Must be a sequence like "0014518E3183"     *     * @param serviceUUID The bluetooth service UUID, in hexadecimal format.     *                    Example: Use "ABCD" instead "0xABCD".     *     * @return Connection The Connection with the service identified by <code>serviceUUID</code> running at the specified <code>device</code>     */    public Connection connectToService(String btDeviceAddress, String serviceUUID) throws BtUtilException {        //Discover devices        Vector devicesFound = discoverDevicesSync();        //Find desired device        RemoteDevice device = null;        for (int i = 0; i < devicesFound.size(); i++) {            device = (RemoteDevice)devicesFound.elementAt(i);            out.println("[BtUtil API] Trying to connect to service " +                    serviceUUID + " at device " + btDeviceAddress +                    ". Device " + device.getBluetoothAddress() + " found.");            if (device.getBluetoothAddress().equals(btDeviceAddress)) {                return connectToService(device, serviceUUID);            }        }        throw new BtUtilException("Device " + btDeviceAddress + " not found.");    }    /**     * Get a Connection from the specified bluetooth service.     *     * @param device The bluetooth device where the service is running.     *               Use the discoverDevicesSync method to get a list of     *               devices in the neighboorhood.     *     * @param serviceUUID The bluetooth service UUID, in hexadecimal format.     *                    Example: Use "ABCD" instead "0xABCD".     *     * @return Connection The Connection with the service identified by     * <code>serviceUUID</code> running at the specified <code>device</code>     */    public Connection connectToService(RemoteDevice device, String serviceUUID) throws BtUtilException {        String serviceUUDIHex = "0x" + serviceUUID;        out.println("[BtUtil API] Going to get connection for service [" + serviceUUDIHex + "].");        try {            Vector services = discoverServicesSync(device, new String[] {serviceUUID});            out.println("[BtUtil API] " + services.size() + " services found with UUID [" + serviceUUDIHex + "].");            if (services == null || services.size() == 0) {                String msg = "[BtUtil API] There is no service with UUID [" + serviceUUDIHex + "]";                out.println(msg);                throw new BtUtilException(msg);            } else if (services.size() > 1) {                //I used to throw an error in this case, but I'm not sure if                //it's really an error or just an API issue.                //String msg = "Error! There are more than one service with UUID [" + serviceUUDIHex + "]";                //out.println(msg);                //throw new BtUtilException(msg);            }            ServiceRecord serviceRecord = (ServiceRecord)services.elementAt(0);            String serviceUrl = serviceRecord.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);            out.println("[BtUtil API] Connecting to service [" + serviceUrl + "]...");            return Connector.open(serviceUrl);        } catch (IOException ex) {            String msg = "[BtUtil API] Failed to create connection with service [" + serviceUUDIHex + "]. " + ex;            out.println(msg);            throw new BtUtilException(msg);        }    }

⌨️ 快捷键说明

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