Aryan
Aryan

Reputation: 11

Bluetooth Android APP

I am a newbie to android Programming i am currently dealing(struggling) with bluetooth programming.

I need to Create an app that

  1. Scans Devices
  2. pair with the Device
  3. Send Data to the Device

I have done the first two parts but I am struck at the 3rd Step I looked up the google chat app but itz too Complex, can any body suggest me where I can get code for such App(including XMLs) Here is the code I am Using

public class MainActivity extends Activity {

BluetoothAdapter adapter;
private static final int REQUEST_ENABLE_BT=1;
private static final int DISCOVERY_REQUEST=2;
Button on, scan, send, discover;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private BluetoothSocket mmSocket=null;
private BluetoothDevice device=null;
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    adapter=BluetoothAdapter.getDefaultAdapter();
    on=(Button)findViewById(R.id.On);
    scan=(Button)findViewById(R.id.Scan);
    send=(Button)findViewById(R.id.Send);
    discover=(Button)findViewById(R.id.Discoverable);
    mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
    mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

    //Switching Bluetooth ON From Here
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    this.registerReceiver(mReceiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    this.registerReceiver(mReceiver, filter);
    final ListView pairedListView = (ListView) findViewById(R.id.paired_list);
    pairedListView.setAdapter(mPairedDevicesArrayAdapter);
    final Set<BluetoothDevice> pairedDevices = adapter.getBondedDevices();

    //Click Listener For Switching Bluetooth On
    on.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) 
        {
            if(adapter==null)
            {
                Toast.makeText(getApplicationContext(), "Device Dosen;t Supports Bluetooth", Toast.LENGTH_SHORT).show();
                finish();
            }else
                if(!adapter.isEnabled())
                {
                    Intent enablebt=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enablebt, REQUEST_ENABLE_BT);
                }else
                    Toast.makeText(getApplicationContext(), "Bluetooth Already On", Toast.LENGTH_SHORT).show();
        }
    });

    //
    discover.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) 
        {
            startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE),DISCOVERY_REQUEST);
        }
    });

    //Scan For Device From Here (Click Listener)
    scan.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) 
        {
            if (pairedDevices.size() > 0) 
            {
                //findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
                for (BluetoothDevice device : pairedDevices) 
                {
                    mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                }
            } else {
                String noDevices ="No Devices Paired";
                mPairedDevicesArrayAdapter.add(noDevices);
            }
            pairedListView.setAdapter(mPairedDevicesArrayAdapter);
            pairedListView.setOnItemClickListener(mDeviceClickListener);
            if (!adapter.isDiscovering())
            {
                Toast.makeText(getApplicationContext(), "devicename", Toast.LENGTH_LONG).show();
                adapter.startDiscovery();
                ListView newDevicesListView = (ListView) findViewById(R.id.list);
                newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
                newDevicesListView.setOnItemClickListener(mDeviceClickListener);
            }


        }
    });
}

//Receiver for found devices From Here
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) 
        {
            //findViewById(R.id.title_found_devices).setVisibility(View.VISIBLE);
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // If it's already paired, skip it, because it's been listed already
            if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
            {
                mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }

            // When discovery is finished, change the Activity title
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) 
        {
            setProgressBarIndeterminateVisibility(false);
            setTitle("Select Device");
            if (mNewDevicesArrayAdapter.getCount() == 0) 
            {
                String noDevices = "No Devices";
                mNewDevicesArrayAdapter.add(noDevices);
            }
        }
    }
};

// 
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) 
    {
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);
        device = adapter.getRemoteDevice(address);
        Toast.makeText(getApplicationContext(), arg3 + "cONNECTING", Toast.LENGTH_SHORT).show();
        try 
        {
            mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            mmSocket.connect();
        } catch (IOException e) {           
            e.printStackTrace();
        }
        Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
        sendMessage("cc");
        String MSG=listenForMessage();
        Toast.makeText(getApplicationContext(), MSG, Toast.LENGTH_SHORT).show();
    }
};

private void sendMessage(String message)
{
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
    OutputStream outStream;
    try 
    {
        outStream = mmSocket.getOutputStream();
        // Add a stop character.
        byte[] byteArray = (message + " ").getBytes();
        byteArray[byteArray.length - 1] = 0;
        outStream.write(byteArray);
    } catch (IOException e) { }
}

private String listenForMessage()
{
    Toast.makeText(getApplicationContext(), "inListen", Toast.LENGTH_SHORT).show();
    String result = "";
    String message="";
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];
    try 
    {
        InputStream instream = mmSocket.getInputStream();
        int bytesRead = -1;
        while (true) 
        {
            bytesRead = instream.read(buffer);
            if (bytesRead != -1) 
            {
                while ((bytesRead == bufferSize) && (buffer[bufferSize-1] != 0))
                {
                    message = message + new String(buffer, 0, bytesRead);
                    bytesRead = instream.read(buffer);
                }
                message = message + new String(buffer, 0, bytesRead - 1);
                Toast.makeText(getApplicationContext(), message + "2", Toast.LENGTH_SHORT).show();
                return result;
            }
        }
    } catch (IOException e) {}
    return result;

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{       
    //super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == DISCOVERY_REQUEST) 
    {
        Toast.makeText(getApplicationContext(), "In Discovery", Toast.LENGTH_SHORT).show();
        boolean isDiscoverable = resultCode > 0;
        int discoverableDuration = resultCode;
        if (isDiscoverable) 
        {
            UUID uuid = UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666");
            String name = "bluetoothserver";
            final BluetoothServerSocket btserver;
            try 
            {
                btserver = adapter.listenUsingRfcommWithServiceRecord(name, uuid);
                Thread acceptThread = new Thread(new Runnable() {
                    public void run() 
                    {
                        try 
                        {
                            BluetoothSocket serverSocket = btserver.accept();
                        } catch (IOException e) {                       
                            e.printStackTrace();
                        }
                    }
                });
                acceptThread.start();
            } catch (IOException e1) {              
                e1.printStackTrace();
            }
        }
    }
}

}

Upvotes: 0

Views: 463

Answers (2)

Ricardo Sousa
Ricardo Sousa

Reputation: 41

My suggestion is that you do a little bit more digging because working with bluetooth is not an easy task. But anyhow, here's my solution for this particular problem:

1 - Bonded devices (Call the Android's Bluetooth default adapter and request already paired (bonded) devices - only because it's simpler for you as a newbie):

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();   
ArrayList<BluetoothDevices> devices = btAdapter.getBondedDevices();

2 - Cancel the discovery (because it's costy) and open communication's connection (Rfcomm) to one device using a BluetoothSocket (choose the device you want to send data to):

btAdapter.cancelDiscovery();
BluetoothSocket btSocket = devices.get(0).createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
btSocket.connect();

3 - Send Data to the Device (simply write to the Socket's out buffer):

byte[] buffer = new byte[1];    
buffer[1] = 'A';   
OutputStream outStream = btSocket.getOutputStream();    
outStream.write (buffer);

Done! Hope this helps. And again: Search more about bluetooth connections because there's way more that this to learn and understand.

Upvotes: 0

khurram
khurram

Reputation: 1362

try this A lightweight library for transferring data between Android devices using Bluetooth.

https://github.com/simonguest/android-btxfr

http://simonguest.com/2013/04/19/transferring-data-via-bluetooth-on-android-android-btxfr/

I hope this will helpful.

Upvotes: 2

Related Questions