如何通过代码将文件从Android设备发送到其他设备

时间:2011-06-03 13:09:52

标签: android bluetooth file-transfer

我想开发使用蓝牙将图像/文件或任何文件从一个Android设备发送到另一个无安卓设备的应用程序。

请有人可以提供帮助或源代码吗?

2 个答案:

答案 0 :(得分:7)

以下是您可以通过蓝牙从Android设备向任何设备发送文件的代码。

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();

                }
            }
        });

享受。 :)

答案 1 :(得分:0)

此应用程序允许两个Android设备通过蓝牙进行双向文本聊天。它演示了所有基本的蓝牙API功能,例如:

  • 扫描其他蓝牙设备
  • 查询本地蓝牙适配器 配对蓝牙设备
  • 建立RFCOMM频道/插座
  • 连接到远程设备
  • 通过蓝牙传输数据

http://developer.android.com/resources/samples/BluetoothChat/index.html