4

I am developing an application in which first we have to search and connect available paired Bluetooth devices. I have done till connection. But after that I have put one screen which asks to choose between Text and file transfer. When I select text then one more screen will open in which there are edittext and button. Whatever user types in edittext and clicks on button that should be transferd to connected BT device like BT chat application. I have gone through BT chat app but it is complex to understand. I want a seperate function which does transferring task. Below is my connection code.

Main.java

public class Main extends Activity implements Runnable 
{
    protected static final String TAG = "TAG";
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    Button mScan;
    BluetoothAdapter mBluetoothAdapter;
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ProgressDialog mBluetoothConnectProgressDialog;
    private BluetoothSocket mBluetoothSocket;
    BluetoothDevice mBluetoothDevice;

    @Override
    public void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);
        mScan = (Button) findViewById(R.id.Scan);
        mScan.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View mView) 
            {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null) 
                {
                    Toast.makeText(Main.this, "Message1", 2000).show();
                } 
                else 
                {
                    if (!mBluetoothAdapter.isEnabled()) 
                    {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                    } 
                    else 
                    {
                        ListPairedDevices();
                        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                    }
                }
            }
        });

    }

    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent) 
    {
        super.onActivityResult(mRequestCode, mResultCode, mDataIntent);

        switch (mRequestCode) 
        {
            case REQUEST_CONNECT_DEVICE:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    Bundle mExtra = mDataIntent.getExtras();
                    String mDeviceAddress = mExtra.getString("DeviceAddress");
                    Log.v(TAG, "Coming incoming address " + mDeviceAddress);
                    mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
                    mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
                    Thread mBlutoothConnectThread = new Thread(this);
                    mBlutoothConnectThread.start();
                    //pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
                }
                break;

            case REQUEST_ENABLE_BT:
                if (mResultCode == Activity.RESULT_OK) 
                {
                    ListPairedDevices();
                    Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
                    startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
                } 
                else 
                {
                    Toast.makeText(Main.this, "Message", 2000).show();
                }
                break;
        }
    }

    private void ListPairedDevices() 
    {
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
        if (mPairedDevices.size() > 0) 
        {
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
            }
        }
    }

    public void run() 
    {
        try 
        {
            mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
            mBluetoothAdapter.cancelDiscovery();
            mBluetoothSocket.connect();
            mHandler.sendEmptyMessage(0);
        }
        catch (IOException eConnectException) 
        {
            Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
             closeSocket(mBluetoothSocket);
             return;
        }
    }

    private void closeSocket(BluetoothSocket nOpenSocket) 
    {
        try 
        {
            nOpenSocket.close();
            Log.d(TAG, "SocketClosed");
        } 
        catch (IOException ex) 
        {
            Log.d(TAG, "CouldNotCloseSocket");
        }
    }

    private Handler mHandler = new Handler() 
    {
        @Override
        public void handleMessage(Message msg) 
        {
            mBluetoothConnectProgressDialog.dismiss();
            Toast.makeText(Main.this, "Device Connected", 5000).show();

            Intent in = new Intent(getBaseContext(), Option.class);
            startActivity(in);

        }
    };
}

DeviceListActivity.java

public class DeviceListActivity extends Activity 
{
    protected static final String TAG = "TAG";
    private BluetoothAdapter mBluetoothAdapter;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;

    @Override
    protected void onCreate(Bundle mSavedInstanceState) 
    {
        super.onCreate(mSavedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.device_list);

        setResult(Activity.RESULT_CANCELED);
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

        ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
        mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
        mPairedListView.setOnItemClickListener(mDeviceClickListener);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();

        if (mPairedDevices.size() > 0) 
        {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice mDevice : mPairedDevices) 
            {
                mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
            }
        } 
        else 
        {
            String mNoDevices = getResources().getText(R.string.none_paired).toString();
            mPairedDevicesArrayAdapter.add(mNoDevices);
        }
    }

    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        if (mBluetoothAdapter != null) 
        {
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() 
    {
        public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong) 
        {
            mBluetoothAdapter.cancelDiscovery();
            String mDeviceInfo = ((TextView) mView).getText().toString();
            String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
            Log.v(TAG, "Device_Address " + mDeviceAddress);

            Bundle mBundle = new Bundle();
            mBundle.putString("DeviceAddress", mDeviceAddress);
            Intent mBackIntent = new Intent();
            mBackIntent.putExtras(mBundle);
            setResult(Activity.RESULT_OK, mBackIntent);
            finish();
        }
    };

}

option.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/file" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/txt" />

</LinearLayout>

message.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" 
        android:hint="@string/hint">

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/send" />

</LinearLayout>
Looking Forward
  • 3,579
  • 8
  • 45
  • 65

3 Answers3

7

Call to following method:

private void sendDataToPairedDevice(String message ,BluetoothDevice device){       
       byte[] toSend = message.getBytes();
        try {
            BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
            OutputStream mmOutStream = socket.getOutputStream();
            mmOutStream.write(toSend);
            // Your Data is sent to  BT connected paired device ENJOY.
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

Now Put following in Your Oncreate of the Activity with EditText.

EditText editText1 = (EditText) findViewById(R.id.editText1);

And Call above method like

sendDataToPairedDevice(editText1.getText() ,mBluetoothDevice);

in The Onclick of your desired button.

thats it. just upvote if you use it, thanks, enjoy buddy.

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61
  • @Shridutt...Hey in (BluetoothDevice device) what parameters I have to pass?? MAC address of destination device???? – Looking Forward Feb 07 '13 at 12:17
  • 2
    just pass your mBluetoothDevice object you have created in your first activity above. – Shridutt Kothari Feb 07 '13 at 12:20
  • @Shridutt...Not getting...I am creating different activity for sending message...How to pass Bluetooth device object to other activity.. – Looking Forward Feb 07 '13 at 12:52
  • for message.xml there is one edittext and send button...For that I have created Message.java. How to pass object in this .java activity... – Looking Forward Feb 07 '13 at 12:53
  • 2
    Ok.. than pass Device Mac address from First Activity to Other Activity through Intent, As Mac Address is a String (So You Should not have any problem in that). Than in Other Activity // Get the device MAC address Like this String address = intent.getExtras().getString("Key for Mac Address"); // Get the BluetoothDevice object BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); – Shridutt Kothari Feb 07 '13 at 13:00
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24131/discussion-between-shridutt-kothari-and-anil-bhatiya) – Shridutt Kothari Feb 07 '13 at 13:51
  • @Shridutt...I have updated my code as you told me...But I am not getting any output... – Looking Forward Feb 28 '13 at 11:59
1
public void onClick(View v) {
                    // TODO Auto-generated method stub




                            mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();

                            byte[] toSend=message1.getBytes();

                            try
                            {

                                final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
                                BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
                                BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
                                OutputStream mmout=socket.getOutputStream();
                                mmout.write(toSend);
                                mmout.flush();
                                mmout.close();
                                socket.close();

                            }
                            catch (IOException e) 
                            {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }





                }
            });
Looking Forward
  • 3,579
  • 8
  • 45
  • 65
  • Until and unless u don't tell me what is ur exact requirement, how would I come to know that u want which code? Better, tell me, what do u want exactly? – Looking Forward Oct 22 '13 at 06:43
  • Actually, I want to send file from one device to another device through bluetooth in my app like u sending text file. – Denny Sharma Oct 22 '13 at 07:06
  • Also text is not sending in my demo, it gives error..So please help me, i need it urgently.... – Denny Sharma Oct 22 '13 at 13:19
  • have u made connection with device on which u want to send data? – Looking Forward Oct 22 '13 at 13:20
  • Please refer my code that i have posted below : Yes i made connection and i m on page that have text or image that i have to send...It give the error that : java.io.IOException: Transport endpoint is not connected – Denny Sharma Oct 23 '13 at 10:07
  • Please see my full code that i have posted again. pleas help me! – Denny Sharma Oct 23 '13 at 11:09
  • Hey anil, please help me dude...i need it urgent! please provide solution on my mail today if it's possible....i really thankful to you for that....mahadevinfotech142@gmail.com – Denny Sharma Oct 24 '13 at 04:43
  • See above in this page yar...My Launcher class : MainActivity.java and all other :: total 3 class..if we install app in my device then anything we have to with another device except making pair? – Denny Sharma Oct 24 '13 at 08:41
  • What r u doing anil..please help me fast if u r able to do..i m really thanksful for that. – Denny Sharma Oct 25 '13 at 05:23
  • Yar, please give me some time...it's really urgent – Denny Sharma Oct 28 '13 at 06:05
1

Finally got the Answer...

    BluetoothAdapter mBluetoothAdapter = null;
    BluetoothDevice m1BluetoothDevice;
    public static BluetoothSocket socket;//Get this value from Main Activity
    Button btn;
    EditText et;

    public static String MacAddressesss; 

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.message);

        btn=(Button)findViewById(R.id.btn);
        et=(EditText)findViewById(R.id.et);

        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                try
                {
                    String msg=et.getText().toString();
                    byte tosend= msg.getBytes();
                    OutputStream out= socket.getOutputStream();
                    out.write(tosend);


                }

                catch(IOException e)
                {
                    e.printStackTrace();
                }


            }
        });






    }


}
Looking Forward
  • 3,579
  • 8
  • 45
  • 65