I wrote a simple application to connect to a bluetooth mini keyboard
but am having trouble with the BluetoothDevice.connect() call.

it gives discovery service failed. I have no problem using the
bluetooth pairing and connect from the bluetooth settings menu. The
same code works with a bluesnap serial to bluetooth device.

Am I missing something obvious?
I've got BLUETOOTH and BLUETOOTH_ADMIN permissions set.
I'm on galaxy tab froyo.

The code is:

package test.com;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;



//import test.com.connect.ClientConnectThread;
import android.app.Activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Toast;
import android.bluetooth.*;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class connect extends Activity {

        static final int ALERT_DIALOG_ID = 1;
        private BtReceiver btReceiver;
        private BluetoothAdapter btAdapter;
        private final Handler handler = new Handler();

        private static final UUID SIMPLE_BT_APP_UUID =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ClientConnectThread clientConnectThread;
    private BluetoothDataCommThread bluetoothDataCommThread;
    private BluetoothDevice remoteDevice;
    private BluetoothSocket activeBluetoothSocket;
    private final String deviceAddress="98:9A:10:12:03:6E";


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




        setContentView(R.layout.main);



        btAdapter=BluetoothAdapter.getDefaultAdapter();

        if(btAdapter==null)
        {
                Toast.makeText(getApplicationContext(), "No Bluetooth
Available",Toast.LENGTH_LONG ).show();
        }else
        {


                if(!btAdapter.isEnabled())
                {
                        Intent enableBtIntent=new
Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);


                        //REQUEST_ENABLE_BT is supposed to be 2 so
                        startActivityForResult(enableBtIntent, 2);

                }

                // we need a broadcast receiver now
            btReceiver = new BtReceiver();
            // register for state change broadcast events
            IntentFilter stateChangedFilter = new
IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(btReceiver, stateChangedFilter);
            // register for discovery events
            IntentFilter actionFoundFilter = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(btReceiver, actionFoundFilter);
            // check current state
            int currentState = btAdapter.getState();

            if (currentState == BluetoothAdapter.STATE_ON) {
                findDevices();
            }



        }

    }

    public void findDevicesHandler(View view){
        int currentState = btAdapter.getState();
        if (currentState == BluetoothAdapter.STATE_ON) {
        Toast.makeText(getApplicationContext(), "Finding
devices",Toast.LENGTH_LONG ).show();
        findDevices();
        }
        else
        {
                Toast.makeText(getApplicationContext(), "Adapter is
off",Toast.LENGTH_LONG ).show();

        }
    }

    protected void onActivityResult(int request,int result,Intent
data)
    {

        if(result==RESULT_OK)
        {
                Toast.makeText(getApplicationContext(), "TURNING ON
BLUETOOTH",Toast.LENGTH_LONG ).show();
        }
    }

    public class BtReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED))
{
                setStatus("Broadcast: Got ACTION_STATE_CHANGED");
                int currentState =
intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.STATE_OFF);
                if (currentState == BluetoothAdapter.STATE_ON) {
                    findDevices();
                }
            } else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                setStatus("Broadcast: Got ACTION_FOUND");
                BluetoothDevice foundDevice =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                setStatus("Device: " + foundDevice.getName() + "@" +
foundDevice.getAddress());
                remoteDevice=foundDevice;
                if(remoteDevice.getAddress().equals(deviceAddress))
                {
                        takeAction();
                 }
                }

            }
        }
    private void setStatus(String string){
        Toast.makeText(getApplicationContext(),
string,Toast.LENGTH_LONG ).show();
    }

    private void findDevices() {
            Set<BluetoothDevice> pairedDevices =
btAdapter.getBondedDevices();
            for (BluetoothDevice pairedDevice : pairedDevices) {
                if (pairedDevice.getAddress().equals(deviceAddress)) {
                    setStatus("Found device: " +
pairedDevice.getName() + "@" + deviceAddress);
                    remoteDevice = pairedDevice;
                }
            }

        if (remoteDevice == null) {
            setStatus("Starting discovery...");
            if (btAdapter.startDiscovery()) {
                setStatus("Discovery started...");
            }

        }
        else
        {
                setStatus("Remote Device
Address:"+remoteDevice.getAddress());
                takeAction();
        }

    }

    private void takeAction()
    {

        Toast.makeText(getApplicationContext(), "GETTING
READY",Toast.LENGTH_LONG).show();


        clientConnectThread = new ClientConnectThread(remoteDevice);
        clientConnectThread.run();


    }

    @Override
    protected void onDestroy() {

        if (clientConnectThread != null) {
            clientConnectThread.stopConnecting();
        }
        if (bluetoothDataCommThread != null) {
            bluetoothDataCommThread.disconnect();
        }
        if (activeBluetoothSocket != null) {
            try {
                activeBluetoothSocket.close();
            } catch (IOException e) {
                //Log.e(DEBUG_TAG, "Failed to close socket", e);
                Toast.makeText(getApplicationContext(),
e.toString(),Toast.LENGTH_LONG ).show();
            }
        }
        btAdapter.cancelDiscovery();
        this.unregisterReceiver(btReceiver);

        super.onDestroy();
    }

    public void doStartDataCommThread() {
        if (activeBluetoothSocket == null) {
            setStatus("Can't start datacomm");
        } else {
            setStatus("Data comm thread starting");
            bluetoothDataCommThread = new
BluetoothDataCommThread(activeBluetoothSocket);
            bluetoothDataCommThread.start();
        }
    }

    private void setLastUsedRemoteBTDevice(String name) {
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        Editor edit = prefs.edit();
        edit.putString("LAST_REMOTE_DEVICE_ADDRESS", name);
        edit.commit();
    }

    // client thread: used to make a synchronous connect call to a
device
    private class ClientConnectThread extends Thread {
        private final BluetoothDevice remoteDevice;
        private  BluetoothSocket clientSocket;

        public ClientConnectThread(BluetoothDevice remoteDevice) {

            this.remoteDevice = remoteDevice;
            clientSocket = null;
        }

        public void run() {
            boolean success = false;
            //success=true;
            try {
                btAdapter.cancelDiscovery();
                //Method m =
remoteDevice.getClass().getMethod("createRfcommSocket",new Class[]
{ int.class});
                //Method m =
remoteDevice.getClass().getMethod("createScoSocket",new Class[]
{ int.class});
                //Method m =
remoteDevice.getClass().getMethod("createInsecureRfcommSocket",new
Class[] { int.class});
                //clientSocket=(BluetoothSocket)m.invoke(remoteDevice,0);
                clientSocket =
remoteDevice.createRfcommSocketToServiceRecord(SIMPLE_BT_APP_UUID);
                clientSocket.connect();
                success = true;
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();
                try {
                    clientSocket.close();
                } catch (IOException e1) {
                    Toast.makeText(getApplicationContext(),"CLOSE:"+
e.toString(),Toast.LENGTH_LONG ).show();
                }
            } catch (SecurityException e) {
                Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();

                        } catch (NoSuchMethodException e) {
                                
Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();
                        } catch (IllegalArgumentException e) {

                                
Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();
                        } /*catch (IllegalAccessException e) {
                                // TODO Auto-generated catch block

                                
Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();
                        } catch (InvocationTargetException e) {
                                // TODO Auto-generated catch block

                                
Toast.makeText(getApplicationContext(),"CONNECT:"+
e.toString(),Toast.LENGTH_LONG ).show();
                        }*/
            final String status;
            if (success) {
                status = "Connected to remote device";
                activeBluetoothSocket = clientSocket;
                // we don't need to keep listening
                //serverListenThread.stopListening();
            } else {
                status = "Failed to connect to remote device";
                activeBluetoothSocket = null;
            }
            handler.post(new Runnable() {
                public void run() {
                    setStatus(status);
 
setLastUsedRemoteBTDevice(remoteDevice.getAddress());
                    doStartDataCommThread();
                }
            });
        }

        public void stopConnecting() {
            try {
                clientSocket.close();
            } catch (Exception e) {
                //Log.e(DEBUG_TAG, "Failed to stop connecting", e);
                Toast.makeText(getApplicationContext(),
"CLOSE2:"+e.toString(),Toast.LENGTH_LONG ).show();
            }
        }
    }

    private class BluetoothDataCommThread extends Thread {
        private final BluetoothSocket dataSocket;
        private final InputStream inData;

        public BluetoothDataCommThread(BluetoothSocket dataSocket) {
            this.dataSocket = dataSocket;
            InputStream inData = null;
            try {
                inData = dataSocket.getInputStream();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),
e.toString(),Toast.LENGTH_LONG ).show();
            }
            this.inData = inData;
        }

        public void run() {
            byte[] readBuffer = new byte[64];
            int readSize = 0;
            try {
                while (true) {

                        readSize=inData.read(readBuffer, 0, 24);


                    final String inStr = new String(readBuffer, 0,
readSize);
                    handler.post(new Runnable() {
                       public void run() {
                           doHandleReceivedCommand(inStr);
                       }
                    });
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
e.toString(),Toast.LENGTH_LONG ).show();
            }
        }



        public void disconnect() {
            try {
                dataSocket.close();
            } catch (Exception e) {
               Toast.makeText(getApplicationContext(),
e.toString(),Toast.LENGTH_LONG ).show();
            }
        }
    }

    public void doHandleReceivedCommand(String rawCommand) {
        String command = rawCommand.trim();
        setStatus("Got: "+ command);

    }
}

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to