Bluetooth Android Изображение / передача файлов
Я делаю приложение, которое сможет получать изображения и файлы, используя соединение Bluetooth. Я не хочу ничего отправлять, только получать. Все онлайн коды для отправки. Я отправляю с Mac и изображения для тестирования в приложение для Android устройства (очки Epson). пожалуйста помоги. Я предоставил код ниже. Соединение сокетов установлено.
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;
}
}
}
}
}