root / mobile / src / com / gonnatrak / mobile / controller / BluetoothHelper.java @ 1

View | Annotate | Download

1
/**
2
 * Created by Andrey Khalzov
3
 * 20.08.2008 23:46:13
4
 */
5
package com.gonnatrak.mobile.controller;
6
7
import javax.bluetooth.*;
8
import java.util.Vector;
9
import java.io.IOException;
10
11
public class BluetoothHelper {
12
13
    public static Vector getBluetoothDevices() throws BluetoothStateException, InterruptedException {
14
        final LocalDevice localDevice = LocalDevice.getLocalDevice();
15
        localDevice.setDiscoverable(DiscoveryAgent.GIAC);
16
        final DiscoveryAgent discoveryAgent = localDevice.getDiscoveryAgent();
17
        final BluetoothDiscoveryListener discoveryListener = new BluetoothDiscoveryListener();
18
        discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
19
        synchronized (discoveryListener) {
20
            if (! discoveryListener.isCompleted()) {
21
                discoveryListener.wait(15000);
22
            }
23
        }
24
        return discoveryListener.getDevices();
25
    }
26
27
    static class BluetoothDiscoveryListener implements DiscoveryListener {
28
29
        private boolean completed = false;
30
        private Vector devices = new Vector();
31
32
        public boolean isCompleted() {
33
            return completed;
34
        }
35
36
        public Vector getDevices() {
37
            return devices;
38
        }
39
40
        public void deviceDiscovered(RemoteDevice remoteDevice, DeviceClass deviceClass) {
41
            String address = remoteDevice.getBluetoothAddress();
42
            String name = null;
43
            try {
44
                name = remoteDevice.getFriendlyName(false);
45
            } catch (IOException e) {}
46
47
            if (name == null || name.trim().length() == 0) {
48
                try {
49
                    name = remoteDevice.getFriendlyName(true);
50
                } catch (IOException e) {}
51
                if (name == null || name.trim().length() == 0) {
52
                    name = address;
53
                }
54
            }
55
56
            BluetoothDevice device = new BluetoothDevice(name, address);
57
            devices.addElement(device);
58
        }
59
60
        public void servicesDiscovered(int i, ServiceRecord[] serviceRecords) {
61
        }
62
63
        public void serviceSearchCompleted(int i, int i1) {
64
        }
65
66
        public synchronized void inquiryCompleted(int i) {
67
            notify();
68
            completed = true;
69
        }
70
    }
71
72
}