当前位置: 首页 > 知识库问答 >
问题:

在android中通过图像传输

贾建茗
2023-03-14
private void sendingContinuePacket(BluetoothGattCharacteristic characteristic,
                                   byte[] CHARACTERS) {
    boolean isComplete = false;
    runOnUiThread(() -> {
        tv_status.setText("Sending Data...!!");
        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);
    });

    // Check the data length is large how many times with Default Data (BLE)

    int times = CHARACTERS.length / DEFAULT_BYTES_IN_CONTINUE_PACKET;
    totalPackets = times;
    Log.i("", "CHARACTERS.length() " + CHARACTERS.length);

    byte[] packetNoByte;
    byte[] sending_continue_hex = new byte[DEFAULT_BYTES_IN_CONTINUE_PACKET];
    for (int time = 0; time <= times; time++) {

        final int remainingTime = time;
        if (!hasDisconnected) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mRelativeLayout.setVisibility(View.VISIBLE);
                    if (totalPackets != 0) {
                        showProgress(totalPackets, remainingTime);
                    }
                }
            });
        } else {
            runOnUiThread(() -> {
                mProgressBar.setProgress(0);
                tv_progress.setText(0 + "%");
                tv_timer.setText("00:00:00");
                tv_imageSize.setText("");
                tv_status.setText("");
                Toast.makeText(PeripheralRoleActivity.this, "Something went wrong, Please Try again", Toast.LENGTH_SHORT).show();
                customHandler.removeCallbacks(updateTimerThread);
            });
            return;
        }
        int a;
        int b;

        /**
         * @param THREAD_SLEEP_TIME_FOR_NOTIFICATION
         * this delay is placed to give a small pause while sending the data packe
         * */
        try {
            Thread.sleep(Constants.THREAD_SLEEP_TIME_FOR_NOTIFICATION);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sentPacket = sentPacket + 1;
        byte[] packetArray = Utils.getUtilsClass().toByteArray(sentPacket);
        packetNoByte = Arrays.copyOf(packetArray, packetArray.length);

        if (time == times) {
            Log.i("", "LAST PACKET ");
            int character_length = CHARACTERS.length
                    - DEFAULT_BYTES_IN_CONTINUE_PACKET * times;
            byte[] sending_last_hex = new byte[character_length];
            a = (sending_continue_hex.length) * time;
            b = a + character_length;
            if(b-a ==0){
                return;
            }
            sending_last_hex = Arrays.copyOfRange(CHARACTERS, a, b);

            byte[] last_packet =
                    new byte[packetNoByte.length + character_length];
            System.arraycopy(packetNoByte, 0, last_packet,
                    0, packetNoByte.length);
            System.arraycopy(sending_last_hex, 0, last_packet,
                    packetNoByte.length, sending_last_hex.length);


            Log.d("Sending packets", Arrays.toString(last_packet));
            // Set value for characteristic
            characteristic.setValue(last_packet);
            notifyCharacteristicChanged();
            isComplete = true;
            customHandler.removeCallbacks(updateTimerThread);
            currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
            Log.d("Collection", "End Time: " + currentDateTimeString);
            Utils.getUtilsClass().sendNotification(getApplicationContext(), "Data Transfer", "Transfer Complete");


        } else {

            Log.i("", "CONTINUE PACKET ");

            a = ((sending_continue_hex.length) * time);
            b = a + DEFAULT_BYTES_IN_CONTINUE_PACKET;

            sending_continue_hex = Arrays.copyOfRange(CHARACTERS, a, b);


            byte[] sending_continue_packet =
                    new byte[packetNoByte.length + sending_continue_hex.length];
            System.arraycopy(packetNoByte, 0, sending_continue_packet,
                    0, packetNoByte.length);
            System.arraycopy(sending_continue_hex, 0, sending_continue_packet,
                    packetNoByte.length, sending_continue_hex.length);


            Log.d("data transfer a", String.valueOf(a));
            Log.d("data transfer b", String.valueOf(b));
            Log.d("data trans bytes", String.valueOf(sending_continue_hex.length));
            if(output == null){
                output = new ByteArrayOutputStream();
            }
            try {
                if {
                    characteristic.setValue(sending_continue_packet);
                    Log.d("Sending packets", Arrays.toString(sending_continue_packet));
                    notifyCharacteristicChanged();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        Log.d("Data byte", "times " + time);

        if (isComplete) {
            characteristic.setValue("Completed");
            notifyCharacteristicChanged();
        }
        runOnUiThread(() -> tv_status.setText("Data sent!!"));
    }
}
private void breakPackets(byte[] CHARACTERS) {
        // Check the data length is large how many times with Default Data (BLE)

        int times = CHARACTERS.length / DEFAULT_BYTES_IN_CONTINUE_PACKET;
        totalPackets = times;
        packetList = new ArrayList<>();
        sendingPacket = 0;
        Log.i("", "CHARACTERS.length() " + CHARACTERS.length);


        byte[] sending_continue_hex = new byte[DEFAULT_BYTES_IN_CONTINUE_PACKET];
        for (int time = 0; time <= times; time++) {


            int a;
            int b;

            if (time == times) {
                Log.i("", "LAST PACKET ");
                int character_length = CHARACTERS.length
                        - DEFAULT_BYTES_IN_CONTINUE_PACKET * times;
                byte[] sending_last_hex = new byte[character_length];
                a = (sending_continue_hex.length) * time;
                b = a + character_length;

                sending_last_hex = Arrays.copyOfRange(CHARACTERS, a, b);
                //packetList is an ArrayList<byte[]>
                packetList.add(sending_last_hex);
                startSendingPackets(sendingPacket);
            } else {
                a = (sending_continue_hex.length) * time;
                b = a + DEFAULT_BYTES_IN_CONTINUE_PACKET;
                sending_continue_hex = Arrays.copyOfRange(CHARACTERS, a, b);

                packetList.add(sending_continue_hex);
            }
            Log.d("Data byte", "times " + time);

        }
    }

    //the following function is used to set the byte[] from the arraylist to the characteristics and then notify the characteristics
     private void startSendingPackets(int packet) {
        isCommand = false;
        mSampleCharacteristic.setValue(packetList.get(packet));
        notifyCharacteristicChanged();
        Log.i("packeting", "Sending  ------------> " + packet);
    }


    /*************************************************/



     @Override
        public void onNotificationSent(BluetoothDevice device, int status) {
            super.onNotificationSent(device, status);
            //check if status is success
            if (status == BluetoothGatt.GATT_SUCCESS) {
            //if status is not successful isExecutable is false and the else loop is executed to resend the same packet that has failed
                if (isExecutable) {
//                    Log.i("packeting", "Sent  ------------> " + sendingPacket);
                    sendingPacket = sendingPacket + 1;
                    int size = packetList.size();
                    if (sendingPacket <= size-1) {

                        startSendingPackets(sendingPacket);

                        Log.d(MainActivity.TAG, "Notification sent. Status: " + status + " sending packet no --" + sendingPacket);
                    } else {
                        sendCommand("Completed");
                    }
                } else {
                    startSendingPackets(sendingPacket);
                    isExecutable = true;
                    Log.d(MainActivity.TAG, "Notification sent. Status: " + status + " sending packet no --" + sendingPacket);
                }
            }else{
            //if status is not successful
                isExecutable = false;

                Log.d(MainActivity.TAG, "Notification sent. fail Status: " + status );
            }


        }

共有1个答案

轩辕华辉
2023-03-14

可以在https://developer.android.com/reference/android/bluetooth/bluetoothGattServerCallback.html#onnotificationsent(android.bluetooth.bluetoothDevice,%20int):

当要发送多个通知时,应用程序必须等待接收到此回调,然后再发送附加通知。

这意味着调用NotifyCharacteristicChanged之后,在收到回调OnNotificationSent之前,不能再次调用NotifyCharacteristicChanged。因此需要删除for-循环并重构代码以遵循API规则。

 类似资料:
  • 问题内容: 有什么办法可以使它工作? [错误] selenium.common.exceptions.InvalidArgumentException:消息:未找到文件:https : //ercess.com//images//events//-Blockchain-2019-36613-banner.png 问题答案: 您首先需要将图像下载到计算机上,然后将其上传… 您可以使用: 然后发送:

  • 问题内容: 我无法通过ajax上传多个文件。这是我的代码。 HTML代码: Ajax代码:- 当我通过Ajax调用upload_business_photo_do()函数时,它无法获取图像$ _FILES [‘file’] [‘name’]的名称 问题答案: 尝试这样使用,它简单又容易 并在控制器中使用像这样 并使用此功能将文件数据转换为多个图像数据的数组 它的工作完美,只需尝试使用它。您无需使用

  • 我的API请求:\u HTTPS://myserver/getcaptchaimage?accesstoken=mytoken 响应:验证码图像 标题: 缓存控制私有内容类型图像/png日期2016年7月4日周一09:15:05 GMT服务器Microsoft IIS/7.5传输编码分块X-AspNet-Version 4.0.30319 X-Powered-By ASP。净额 我的代码(http

  • 我在用这个 将图像上传到gupshup whatsapp chatbot的格式,但图像没有被发送,它显示的错误是

  • JPEG、PNG 或 GIF 图像资源可以从 PSD 文件图层或图层组中的内容生成。将受支持的图像格式扩展添加到图层名称或图层组名称时,会自动生成资源。(可选)您也可以指定所生成图像资源的品质和大小参数。 从 PSD 文件生成图像资源对于多设备 Web 设计来说尤其有用。 视频:在 Photoshop 中生成 Web 资源视频:在 Photoshop 中生成 Web 资源这段视频会向您介绍如何通过