Java 蓝牙Android图像/文件传输
我正在做一个应用程序,将能够接收图像和文件使用蓝牙连接。我不想发送任何东西,只想接收。所有在线代码都用于发送。我从Mac和图像发送到android设备(爱普生眼镜)应用程序进行测试。请帮忙。我提供了下面的代码。已建立套接字连接Java 蓝牙Android图像/文件传输,java,android,image,bluetooth,data-transfer,Java,Android,Image,Bluetooth,Data Transfer,我正在做一个应用程序,将能够接收图像和文件使用蓝牙连接。我不想发送任何东西,只想接收。所有在线代码都用于发送。我从Mac和图像发送到android设备(爱普生眼镜)应用程序进行测试。请帮忙。我提供了下面的代码。已建立套接字连接 public class Mine extends Activity { private TextView SampleText; private BluetoothAdapter mBluetoothAdapter = null; private Bluetooth
public class Mine extends Activity {
private TextView SampleText;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mmDevice;
private BluetoothSocket mmSocket;
public static final UUID Glasses_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private final String TAG = "debugging";
static final int IMAGE_QUALITY = 100;
ImageView pointerIcon;
int duration = Toast.LENGTH_SHORT;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
private final String TEMP_IMAGE_FILE_NAME = "BTimage.jpg" + timeStamp +"_";
//Handler used to send data to here
// it converts byte array to string and saves it to write message
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i(TAG, "---In Handler---");
super.handleMessage(msg);
switch(msg.what) {
//do something
case 1:
ConnectedThread mConnectedThread = new ConnectedThread((BluetoothSocket) msg.obj);
mConnectedThread.start();
break;
case 2:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Toast.makeText(getApplicationContext(), readMessage, duration).show();
break;
case 3: //data received -image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeByteArray(((byte[]) msg.obj), 0, ((byte[]) msg.obj).length, options);
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setImageBitmap(image);
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mine);
//sets the background as transparent black
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
winParams.flags |= 0x80000000;
win.setAttributes(winParams);
SampleText = (TextView) findViewById(R.id.SampleText);
pointerIcon = (ImageView) findViewById(R.id.icon);
pointerIcon.setVisibility(View.VISIBLE);
SampleText.setVisibility(View.VISIBLE);
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(200); //You can manage the blinking time with this parameter
anim.setStartOffset(20);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
SampleText.startAnimation(anim);
// BLUETOOTH section
//make device discoverable for 300sec
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); // for extra time discovery
startActivity(discoverableIntent);
Log.i(TAG, "---Making device discoverable for 300 seconds---");
// get local bluetooth (glasses)
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//checks if bluetooth is enabled, if its not it enables it
if (!mBluetoothAdapter.isEnabled()) {
Intent EnableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(EnableBluetooth, 1);
///Toast.makeText(getApplicationContext(), "Bluetooth Enabled", duration).show();
Log.i(TAG, "---Bluetooth is now on---");
finish();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth Already On", duration).show();
}
// get list of paired devices
// The paired device is saved into storage "Set".
Set <BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//if there is paired devices
if (pairedDevices.size() > 0) {
//loop through paired devices
for (BluetoothDevice device : pairedDevices) {
mmDevice = device;
Toast.makeText(getApplicationContext(), "Paired Device: " + device.getName() + device.getAddress(),
duration).show();
Log.i(TAG, "---Show on screen Device connected");
}
}
ConnectThread mConnectThread = new ConnectThread(mmDevice);
mConnectThread.start();
}
private class ConnectThread extends Thread {
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null; // temporary object assigned to mmSocket later
mmDevice = device;
Log.i(TAG, "---Connecting---");
UUID SERIAL_UUID = device.getUuids()[0].getUuid(); // to identify the app uuid
Log.i(TAG, String.valueOf(SERIAL_UUID));
//Get Bluetooth socket to connect with a bluetooth device
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(Glasses_UUID);
} catch (IOException e) {
Log.e(TAG, "create Socket failed!", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "---BEGIN ConnectThread - RUN() ---");
setName("ConnectThread");
mBluetoothAdapter.cancelDiscovery(); // because it slows down a connection
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
Log.i(TAG, "---Connecting to socket...----");
///mmDevice= mBluetoothAdapter.getRemoteDevice("68:A8:6D:2B:77:FD");
if(!mmSocket.isConnected()) //to prevent connecting again and again
mmSocket.connect();
Log.i(TAG, "---Connected to Socket...----");
mHandler.obtainMessage(1, mmSocket).sendToTarget();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
Log.i(TAG, "---Unable to connect, Socket Closing...----");
mmSocket.close();
Log.i(TAG, "---Socket Closed----");
} catch (IOException closeException) {
Log.e(TAG, "--unable to close socket!--", closeException);
}
return;
}
// Do work to manage the connection (in a separate thread)
// start thread
}
/**
* Will cancel an in-progress connection, and close the socket
*/
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "---closing socket failed!---", e);
}
}
}
/**
*
* Send and receive data Thread
* Handles all incoming transmissions.
*/
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
public ConnectedThread(BluetoothSocket socket) {
Log.i(TAG, "---ConnectedThread Start----");
mmSocket = socket;
InputStream tmpIn = null;
// get the temporary input streams
try {
Log.i(TAG, "---getting input tmp----");
tmpIn = socket.getInputStream(); //getinput stream gives accesss to the socket
} catch (IOException e) {
Log.e(TAG, "---Error getting streams!----", e);
}
mmInStream = tmpIn;
}
public void run () {
Log.i(TAG, "---BEGIN ConnectedThread - Run()---");
int bufferSize= 2097152; //This is set to 2 MB
byte[] buffer; // buffer store for the stream
int bytes; //bytes returned from read()
ByteArrayOutputStream compressedImageStream = new ByteArrayOutputStream();
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
Log.i(TAG, "---Reading Data...---");
buffer = new byte[bufferSize]; // buffer store for stream
bytes = mmInStream.read(buffer, 0, buffer.length); // bytes returned from read()
compressedImageStream.write(buffer, 0, bytes);
//Send the obtained bytes to the UI activity
// mHandler.obtainMessage(2, bytes, -1, buffer).sendToTarget();
File file = new File(Environment.getExternalStorageDirectory(), TEMP_IMAGE_FILE_NAME); // create image file in storage - destination path and filename
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap image = BitmapFactory.decodeFile(file.getAbsolutePath(), options); // this is to read the image from the storage /decoding
image.compress(Bitmap.CompressFormat.PNG, IMAGE_QUALITY, compressedImageStream); //save as PNG or JPEG here
byte[] compressedImage = compressedImageStream.toByteArray();
Log.v(TAG, "Compressed image size: " + compressedImage.length);
Message message = new Message();
message.obj = compressedImage;
mHandler.sendMessage(message);
// Display the image locally
ImageView imageView = (ImageView) findViewById(R.id.imageview);
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap(image);
//Intent intent=new Intent();
//intent.setAction("received");
//sendBroadcast(intent);
Log.i(TAG, "---reading data successful---");
} catch (IOException e) {
Log.e(TAG, "---disconnected!---(Reading problem)", e);
break;
}
}
}
}
}
公共类挖掘扩展活动{
私有文本视图示例文本;
私有BluetoothAdapter mBluetoothAdapter=null;
私人蓝牙设备;
私人蓝牙插座;
公共静态最终UUID玻璃_UUID=UUID.fromString(“00001101-0000-1000-8000-00805f9b34fb”);
私有最终字符串标记=“调试”;
静态最终整型图像质量=100;
图像视点;
int duration=Toast.LENGTH\u SHORT;
字符串时间戳=新的SimpleDateFormat(“yyyyMMdd_HHmmss”)。格式(新日期();
私有最终字符串TEMP_IMAGE_FILE_NAME=“BTimage.jpg”+时间戳+”;
//用于将数据发送到此处的处理程序
//它将字节数组转换为字符串,并将其保存为写入消息
Handler mHandler=新处理程序(){
@凌驾
公共无效handleMessage(消息消息消息){
Log.i(处理程序中的标记“---”);
超级handleMessage(msg);
开关(msg.what){
//做点什么
案例1:
ConnectedThread mConnectedThread=newconnectedThread((BluetoothSocket)msg.obj);
mConnectedThread.start();
打破
案例2:
字节[]readBuf=(字节[])msg.obj;
//从缓冲区中的有效字节构造字符串
String readMessage=新字符串(readBuf,0,msg.arg1);
Toast.makeText(getApplicationContext(),readMessage,duration).show();
打破
案例3://收到的数据-图像
BitmapFactory.Options=new-BitmapFactory.Options();
options.inSampleSize=2;
位图图像=BitmapFactory.decodeByteArray(((字节[])msg.obj),0,((字节[])msg.obj).长度,选项);
ImageView ImageView=(ImageView)findViewById(R.id.ImageView);
设置图像位图(图像);
打破
}
}
};
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mine);
//将背景设置为透明黑色
windowwin=getWindow();
WindowManager.LayoutParams winParams=win.getAttributes();
winParams.flags |=0x8000000;
win.setAttributes(winParams);
SampleText=(TextView)findViewById(R.id.SampleText);
pointerIcon=(ImageView)findViewById(R.id.icon);
pointerIcon.setVisibility(View.VISIBLE);
SampleText.setVisibility(View.VISIBLE);
动画动画=新的AlphaAnimation(0.0f,1.0f);
anim.setDuration(200);//您可以使用此参数管理闪烁时间
动画设置开始偏移(20);
动画设置重复模式(动画反转);
anim.setRepeatCount(Animation.INFINITE);
SampleText.startAnimation(动画);
//蓝牙部分
//使设备可发现300秒
Intent discoverableIntent=新意图(BluetoothAdapter.ACTION\u REQUEST\u DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);//用于额外时间发现
星触觉(可发现的意图);
Log.i(标记“---使设备在300秒内可被发现---”);
//获取本地蓝牙(眼镜)
mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//检查蓝牙是否已启用,如果未启用,则启用
如果(!mBluetoothAdapter.isEnabled()){
意图启用Bluetooth=新意图(BluetoothAdapter.ACTION\u REQUEST\u ENABLE);
startActivityForResult(启用蓝牙,1);
///Toast.makeText(getApplicationContext(),“启用蓝牙”,持续时间).show();
Log.i(标记“--Bluetooth现在处于打开状态---”);
完成();
}否则{
Toast.makeText(getApplicationContext(),“蓝牙已打开”,duration.show();
}
//获取配对设备的列表
//配对设备保存到存储器“Set”中。
设置pairedDevices=mBluetoothAdapter.getBondedDevices();
//如果有配对设备
如果(pairedDevices.size()>0){
//循环通过配对设备
用于(蓝牙设备:pairedDevices){
mmDevice=设备;
Toast.makeText(getApplicationContext(),“配对设备:”+Device.getName()+Device.getAddress(),
持续时间);
Log.i(标签“---显示已连接的屏幕设备”);
}
}
ConnectThread mConnectThread=新的ConnectThread(mmDevice);
mConnectThread.start();
}
私有类ConnectThread扩展线程{
公共连接线程(蓝牙设备){
BluetoothSocket tmp=null;//稍后分配给mmSocket的临时对象
mmDevice=设备;
Log.i(标记“--Connecting--”);
UUID SERIAL_UUID=device.getUuids()[0].getUuid();//用于标识应用程序UUID
Log.i(TAG,String.valueOf(SERIAL_UUID));
//获取蓝牙插座以连接蓝牙设备
试一试{
tmp=设备.createInsurerCommsocketToServiceRecord(眼镜UUID);
}捕获(IOE异常){
Log.e(标记“创建套接字失败!”,e);
}
mmSocket=tmp;
}
公开募捐{
i(标记“--BEGIN ConnectThread-RUN()--”;
设置名称(“连接线程”);
mBluetoothAdapter.cancelDiscovery();//因为它会减慢连接速度
试一试{
//通过插座连接设备。这将阻止
//直到它成功或抛出异常
Log.i(标记“----连接到插座…”);
///mmDevice=mBluetoothAdapter.getRemoteDevice(“68:A8:6D:2B:77:FD”);
如果(!mmSocket.isConnected())//防止再次连接