How to send file from Android device to other device through Bluetooth by code

Here is the code from which you can send file via bluetooth from android device to any device.

btnOk.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) 
            {
                txtContent = (EditText)findViewById(R.id.txtContent);
                imageView = (ImageView)findViewById(R.id.imageView);
                linearLayout = (LinearLayout)findViewById(R.id.linearLayout);

                viewToBeConverted = (TextView) findViewById(R.id.hello);
                linearLayout.setDrawingCacheEnabled(true);

                //Toast.makeText(MainActivity.this, file.toString(), Toast.LENGTH_LONG).show();
                try
                {
                    if(file.exists())
                    {
                        file.delete();
                    }
                    out = new FileOutputStream(file);
                }
                catch (Exception e) 
                {
                    Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                }


                viewToBeConverted.setText(txtContent.getText().toString());
                viewToBeConverted.setDrawingCacheEnabled(true);

               // Toast.makeText(MainActivity.this, " " + viewToBeConverted.getDrawingCache(), Toast.LENGTH_LONG).show();
                txtContent.setText("");

                Bitmap viewBitmap = linearLayout.getDrawingCache();


                linearLayout.setVisibility(1);
                imageView.setImageBitmap(viewBitmap);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                viewBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object

                byte[] b = baos.toByteArray();  

                try 
                {

                    out.write(b);
                    out.flush();
                    out.close();

                    Intent intent = new Intent();  
                    intent.setAction(Intent.ACTION_SEND);  
                    intent.setType("image/png");
                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file) );  
                    startActivity(intent);
                }
                catch (Exception e) 
                {
                    Toast.makeText(MainActivity.this, " " + e.getMessage(), Toast.LENGTH_LONG).show();

                }
            }
        });

Enjoy. 🙂

Leave a Comment