Code example for BluetoothAdapter

Methods: cancelDiscovery, getRemoteDevice, isEnabled

0
	public boolean connected = false;
 
	public TBlue(String address) {
		this.address = address.toUpperCase();
		localAdapter = BluetoothAdapter.getDefaultAdapter();
		if ((localAdapter != null) && localAdapter.isEnabled()) {
			Log.i(TAG, "Bluetooth adapter found and enabled on phone. ");
		} else { 
			Log.e(TAG, "Bluetooth adapter NOT FOUND or NOT ENABLED!");
			return; 
		} 
		if (connect()) { 
			connected = true;
		} else { 
			connected = false;
		} 
	} 
 
	public boolean connect() { 
		Log.i(TAG, "Bluetooth connecting to " + address + "...");
		try { 
			remoteDevice = localAdapter.getRemoteDevice(address);
		} catch (IllegalArgumentException e) {
			Log.e(TAG, "Failed to get remote device with MAC address."
					+ "Wrong format? MAC address must be upper case. ", e);
			return false; 
		} 
 
		Log.i(TAG, "Creating RFCOMM socket...");
		try { 
			Method m = remoteDevice.getClass().getMethod("createRfcommSocket",
					new Class[] { int.class });
			socket = (BluetoothSocket) m.invoke(remoteDevice, 1);
			Log.i(TAG, "RFCOMM socket created.");
		} catch (NoSuchMethodException e) {
			Log.i(TAG, "Could not invoke createRfcommSocket.");
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			Log.i(TAG, "Bad argument with createRfcommSocket.");
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			Log.i(TAG, "Illegal access with createRfcommSocket.");
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			Log.i(TAG, "Invocation target exception: createRfcommSocket.");
			e.printStackTrace();
		} 
		Log.i(TAG, "Got socket for device " + socket.getRemoteDevice());
		localAdapter.cancelDiscovery();
 
		Log.i(TAG, "Connecting socket...");
		try { 
			socket.connect();
			Log.i(TAG, "Socket connected.");