Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/199.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 可调谐图像传输_Java_Android_Image_Bluetooth Lowenergy - Fatal编程技术网

Java 可调谐图像传输

Java 可调谐图像传输,java,android,image,bluetooth-lowenergy,Java,Android,Image,Bluetooth Lowenergy,下面是将图像转换为字节数组并发送到ble设备的代码 我无法发送完整的数据,它几乎停止在1kb 向ble发送大数据的方法有哪些。 在数据传输中使用延迟是否合适?如果合适,您是否可以共享代码 如果任何人有任何代码发送数据高达1mb,请不要共享 公共类RXTX活动扩展活动{ byte[] imageInByte,SendByte; private static int IMG_RESULT = 1; String ImageDecode; ImageView imageViewLoad; Button

下面是将图像转换为字节数组并发送到ble设备的代码 我无法发送完整的数据,它几乎停止在1kb

向ble发送大数据的方法有哪些。 在数据传输中使用延迟是否合适?如果合适,您是否可以共享代码

如果任何人有任何代码发送数据高达1mb,请不要共享

公共类RXTX活动扩展活动{

byte[] imageInByte,SendByte;
private static int IMG_RESULT = 1;
String ImageDecode;
ImageView imageViewLoad;
Button LoadImage;
Intent intent;
String[] FILE;

String[] SAImage,SAsent;

private final static String TAG = DeviceControlActivity.class.getSimpleName();

public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

private TextView mCharaDescriptor;
private TextView mConnectionState;
private TextView mDataField;
private TextView mDeviceAddressTextView;

private String mServiceUUID, mDeviceAddress;
private String mCharaUUID, mDeviceName;
private BluetoothLeService mBluetoothLeService;
private ArrayList<ArrayList<BluetoothGattCharacteristic>> mGattCharacteristics =
        new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
private boolean mConnected = true;
private BluetoothGattCharacteristic mNotifyCharacteristic;
private Button EditButton;
private Button CharaSubscribeButton;
private EditText EditText;

private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private String CHARA_DESC = "";
private String properties = "";

private Context context = this;

// Code to manage Service lifecycle.
private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder service) {
        mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
        if (!mBluetoothLeService.initialize()) {
            Log.e(TAG, "Unable to initialize Bluetooth");
            finish();
        }
        // Automatically connects to the device upon successful start-up initialization.
        mBluetoothLeService.connect(mDeviceAddress);

        mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        mBluetoothLeService = null;
    }
};

// Handles various events fired by the Service.
// ACTION_GATT_CONNECTED: connected to a GATT server.
// ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
// ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
// ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
//                        or notification operations.
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(final Context context, Intent intent) {
        final String action = intent.getAction();
        switch (action) {
            case BluetoothLeService.ACTION_GATT_CONNECTED:
                mConnected = true;
                updateConnectionState(R.string.connected);
                invalidateOptionsMenu();
                break;
            case BluetoothLeService.ACTION_GATT_DISCONNECTED:
                mConnected = false;
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                break;
            case BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED:
                break;
            case BluetoothLeService.ACTION_DATA_AVAILABLE:
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "Data Received!", Toast.LENGTH_SHORT).show();
                    }
                });
                displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
                break;
            case BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE:
                Log.i("Receiving data", "Broadcast received");
                displayDescriptor(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
            default:
                break;
        }
    }
};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data_transfer);

    imageViewLoad = (ImageView) findViewById(R.id.imageView1);
    LoadImage = (Button)findViewById(R.id.button1);

    LoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(intent, IMG_RESULT);

        }
    });



    final Intent intent = getIntent();

    Log.i("OnCreate", "Created");

    mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);
    mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
    mServiceUUID = intent.getStringExtra("Service UUID");
    mCharaUUID = intent.getStringExtra("Characteristic UUID");
    CHARA_DESC = intent.getStringExtra("Characteristic Descriptor");
    properties = intent.getStringExtra("Characteristic properties");

    // Sets up UI references.
    ((TextView) findViewById(R.id.device_address_rxtx)).setText("Characteristic UUID: " + mCharaUUID);
    ((TextView) findViewById(R.id.characteristic_Descriptor)).setText("Characteristic Descriptor: " + CHARA_DESC);
    ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);

    mConnectionState = (TextView) findViewById(R.id.connection_state);
    mConnectionState.setText("Connected");

    mDataField = (TextView) findViewById(R.id.data_value);
    EditText = (EditText) findViewById(R.id.characteristicEditText);
    EditButton = (Button) findViewById(R.id.characteristicButton);
    CharaSubscribeButton = (Button) findViewById(R.id.characteristic_Subscribe);
    mCharaDescriptor = (TextView) findViewById(R.id.characteristic_Descriptor);

    EditButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String str = EditText.getText().toString();
            mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "Message Sent!", Toast.LENGTH_SHORT).show();
                }
            });
            mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
        }
    });

    CharaSubscribeButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (properties.indexOf("Indicate") >= 0) {
                mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 1);
            } else if (properties.indexOf("Notify") >= 0) {
                mBluetoothLeService.subscribeCustomCharacteristic(mServiceUUID, mCharaUUID, 2);
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "Characteristic Subscribed!", Toast.LENGTH_SHORT).show();
                }
            });
            mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
        }
    });

    checkProperties();
    getActionBar().setTitle(mDeviceName);
    getActionBar().setDisplayHomeAsUpEnabled(true);
    Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
    bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}

private void checkProperties() {
    if (properties.indexOf("Write") >= 0) {
    } else {
        EditButton.setEnabled(false);
    }
    if (properties.indexOf("Indicate") >= 0) {
    } else {
        CharaSubscribeButton.setEnabled(false);
    }
}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
    if (mBluetoothLeService != null) {
        final boolean result = mBluetoothLeService.connect(mDeviceAddress);
        Log.d(TAG, "Connect request result=" + result);
    }
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(mGattUpdateReceiver);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    unbindService(mServiceConnection);
    mBluetoothLeService = null;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.gatt_services, menu);
    if (mConnected) {
        menu.findItem(R.id.menu_connect).setVisible(false);
        menu.findItem(R.id.menu_disconnect).setVisible(true);
    } else {
        menu.findItem(R.id.menu_connect).setVisible(true);
        menu.findItem(R.id.menu_disconnect).setVisible(false);
    }
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_connect:
            mBluetoothLeService.connect(mDeviceAddress);
            return true;
        case R.id.menu_disconnect:
            mBluetoothLeService.disconnect();
            return true;
        case android.R.id.home:
            onBackPressed();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

private void updateConnectionState(final int resourceId) {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mConnectionState.setText(resourceId);
        }
    });
}

private void displayData(String data) {
    if (data != null) {
        mDataField.setText(data);
    }
}

private void displayDescriptor(final String data) {
    if( data != null){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mCharaDescriptor.setText(mCharaDescriptor.getText().toString() + "\n" + data);
            }
        });
    }
}


private static IntentFilter makeGattUpdateIntentFilter() {
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
    intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
    intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
    intentFilter.addAction(BluetoothLeService.ACTION_DESCRIPTOR_AVAILABLE);
    return intentFilter;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {

        if (requestCode == IMG_RESULT && resultCode == RESULT_OK
                && null != data) {


            Uri URI = data.getData();
            String[] FILE = { MediaStore.Images.Media.DATA };


            Cursor cursor = getContentResolver().query(URI,
                    FILE, null, null, null);

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(FILE[0]);
            ImageDecode = cursor.getString(columnIndex);
            cursor.close();

            imageViewLoad.setImageBitmap(BitmapFactory
                    .decodeFile(ImageDecode));

        }
    } catch (Exception e) {
        Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
                .show();
    }

}


public void ClickConvert(View view) {

    TextView txtView;
    txtView=(TextView)findViewById(R.id.textview_byte);

    ImageView imageView = (ImageView) findViewById(R.id.imageView1);
    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    imageInByte = baos.toByteArray();
    String response ;
    response = byteArrayToString(imageInByte);
    // response = new sun.misc.BASE64Encoder().encode(imageInByte);
    //String s = javax.xml.bind.DatatypeConverter.printHexBinary(imageInByte);
    //String str = new String(imageInByte, "UTF-8");
    txtView.setText(response);


}
public static String byteArrayToString(byte[] data){
    String response = Arrays.toString(data);

    String[] byteValues = response.substring(1, response.length() - 1).split(",");
    byte[] bytes = new byte[byteValues.length];

    for (int i=0, len=bytes.length; i<len; i++) {
        bytes[i] = Byte.parseByte(byteValues[i].trim());
    }

    String str = new String(bytes);
    return str.toLowerCase();
}




public void ClickImage(View view) {

    final int num= imageInByte.length;
    int i,j,l,h;
       j=num/20;
    Toast.makeText(getApplicationContext(), "loop : " + j,  Toast.LENGTH_SHORT).show();
    for (i = 0; i <= j; i++) {
           l=20*i;
           h=20*(i+1);
           SystemClock.sleep(40); //ms
           SendByte = Arrays.copyOfRange(imageInByte, l, h);
           String str = new String(SendByte);
           mBluetoothLeService.writeCustomCharacteristic(str, mServiceUUID, mCharaUUID);
           runOnUiThread(new Runnable() {
               @Override
               public void run() {
               }
           });
           mBluetoothLeService.readCustomDescriptor(mCharaUUID, mServiceUUID);
   }
}

请分享您完整的writeCustomCharacteristic方法代码。发送的部分可能重复?每个字节数组只有一小部分?只有前n个字节数组?请更具体地说明您的错误。@Christopher我已经发布了完整的代码,我添加了40毫秒的延迟,并且能够传输完整的数据,但这几乎花费了我的时间20米时间任何人都可以建议延迟以外的任何其他方法吗?您似乎认为您的设备按照代码所述进行操作。通常情况下并非如此。缓冲区可能已满,连接可能会丢失,等等。我知道您希望在延迟40毫秒后发送写请求,但仅因为代码如此规定,无法保证设备实际上是这样的。
 public void writeCustomCharacteristic(String str, String serviceUuid, String charaUuid) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    /*check if the service is available on the device*/
    BluetoothGattService mCustomService = mBluetoothGatt.getService(UUID.fromString(serviceUuid));
    if(mCustomService == null){
        Log.w(TAG, "Custom BLE Service not found");
        return;
    }

    /*byte[] value = parseHex(str);

    *//*get the read characteristic from the service*//*
    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
    mWriteCharacteristic.setValue(value);
    mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);*/

    byte[] strBytes = str.getBytes();

    BluetoothGattCharacteristic mWriteCharacteristic = mCustomService.getCharacteristic(UUID.fromString(charaUuid));
    mWriteCharacteristic.setValue(strBytes);
    mBluetoothGatt.writeCharacteristic(mWriteCharacteristic);

}