Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.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 - Fatal编程技术网

Java 构造此函数的正确方法

Java 构造此函数的正确方法,java,android,Java,Android,我正在开发一款通过蓝牙与另一块PCB进行通信的应用程序。它由3个Seekbar组成,用于调节PCB 3个参数的值 结构如下: 1. Send petition string for read the first value 2. Receive the first value 3. Send petition string for read the second value 4. Receive the second value 5. Send petition string for the t

我正在开发一款通过蓝牙与另一块PCB进行通信的应用程序。它由3个Seekbar组成,用于调节PCB 3个参数的值

结构如下:

1. Send petition string for read the first value
2. Receive the first value
3. Send petition string for read the second value
4. Receive the second value
5. Send petition string for the third value
6. Receive the third value
我已经做到了,像我这样的新手可以做到最好。它是有效的,但有时会失败,所以,我知道还有其他方法可以让它工作得完美

所以,这是一个请求,希望有一个慷慨的人看看代码,并帮助我与它

当我们按下“读取值”按钮时,就会发生这种情况。必须注意的是,我使用可运行的处理程序在传输之间等待1秒,让应用程序读取每个请求的答案:

public void receiveValues() {       

    /**Petition string that is sent to the PCB to request the variable's value*/
    final String message_full1 = 2b e1 b4 e9 ff 1f b5;  //variable 1
    final String message_full2 = 2b e1 b8 e9 ff 1f b3;  //variable 2
    final String message_full3 = 2b e1 bc e9 ff 1f b1;  //variable 3
    final String message_full4 = 2b e0 bc f3 ff 1f 7c;  //save request
    final String message_full5 = 2b e0 be f3 ff 1f 7a;  //save status


    /*Send the first string to the PCB*/
    byte[] send1 = message_full1.getBytes();
    GlobalVar.mTransmission.write(send1);


    /**Delay to wait until it receives the answer to the petition above*/
    read1_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**Read write confirmation after 1s = 1000ms*/
            String inpuRead = "2b 00 ff fe c7 80";  //This string is what I receive as an answer via bluetooth

            /**We check that the received string is not null, to avoid program crash*/
            if (inpuRead != null) { //|| !inpuRead.equals("")) {

                /*If it nos null, then we call the next function*/
                int splitInt = splitReceivedString (inpuRead);  //This function is declared below and extracts from the string , only the chars that we need.
                receive1 = splitInt;
                Toast.makeText(getApplicationContext(), "Loading values", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Communication error", Toast.LENGTH_SHORT).show();
            }
        }
    }, 1000);


    /**Delay to wait to send de second petition string*/
    write2_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**write message 2 after 1s = 1000ms*/
            byte[] send2 = message_full2.getBytes();
            GlobalVar.mTransmission.write(send2);
        }
    }, 2000);

    /**Delay to wait until it receives the answer to the second petition string*/
    read2_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**Read write confirmation after 1s = 1000ms*/
            String inpuRead = "2b 00 ff fe c7 80";

            if (inpuRead != null) {
                int splitInt = splitReceivedString (inpuRead);
                receive2 = splitInt;
            }
            else {
                Toast.makeText(getApplicationContext(), Communication error, Toast.LENGTH_SHORT).show();
            }
        }
    }, 3000);

    /**Delay to wait to send de third petition string*/
    write3_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**write message 3 after 1s = 1000ms*/
            byte[] send3 = message_full3.getBytes();
            GlobalVar.mTransmission.write(send3);
        }
    }, 4000);

    /**Delay to wait until it receives the answer to the third petition string*/
    read3_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**Read write confirmation after 1s = 1000ms*/
            String inpuRead = "2b 00 ff fe c7 80";

            if (inpuRead != null) {
                int splitInt = splitReceivedString (inpuRead);
                receive3 = splitInt;

                /**Set loaded values on seekbars*/
                bar1.setProgress(receive1);
                bar2.setProgress(receive2);
                bar3.setProgress(receive3);

                /**Message indicating the end of the transmission*/
                Toast.makeText(getApplicationContext(), "Values loaded!", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Communication error", Toast.LENGTH_SHORT).show();
            }
        }
    }, 5000);

    /**This makes a save request on the pCB*/
    write4_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**write message 3 after 1s = 1000ms*/
            byte[] send4 = message_full4.getBytes();
            GlobalVar.mTransmission.write(send4);
        }
    }, 6000);

    /**This request a save statos on the PCB*/
    write5_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            /**write message 3 after 1s = 1000ms*/
            byte[] send5 = message_full5.getBytes();
            GlobalVar.mTransmission.write(send5);

            /**Reset out string buffer to zero*/
            GlobalVar.mOutStringBuffer.setLength(0);
        }
    }, 7000);
}


/**
 * FUNCTION THAT SPLITS THE RECEIVED STRING TO GET THE DESIRED VALUES
 */

private int splitReceivedString (String s) {  //For example, s = 2b 00 ff fe c7 80

    StringTokenizer tokens = new StringTokenizer(s," ");
    String one = tokens.nextToken();
    String two = tokens.nextToken();
    String three = tokens.nextToken();
    String four = tokens.nextToken();
    String five = tokens.nextToken();
    String six = tokens.nextToken();

    /**The next strings are whose got the seekbar's value*/  //f.e: "fffec780"
    received_hexValue = three + four + five + six;
    received_hexValue = received_hexValue.trim();


    /**Conversion from hex to int to set the seekbar's values*/
    int_value_receive = (int)Long.parseLong(received_hexValue, 16);
    int_value_receive = -200000 - int_value_receive;
    newIntValue = (int_value_receive * 100) / (200000 * (-1));

    return newIntValue;  //For this hex value, the int value to introduce in the seekbar is "60"
}
更新-添加问题

我想做的第一件事,但我不知道怎么做,当它进入一个
如果
,如果这是真的,那么它必须继续执行代码,但是如果它不是真的,那么它应该退出函数并停止执行代码。但按照我的方式,它仍在继续执行

我的意思是,我有时会遇到的崩溃是,有时,而不是以这种方式获取结构:

1. Send petition string for read the first value
2. Receive the first value
3. Send petition string for read the second value
4. Receive the second value
...
它的作用类似于:

1. Send petition string for read the first value
2. Send petition string for read the second value
3. Receive the first value
...

所以这里就是它崩溃的地方。

如果你想让任务轮流执行,你不需要额外的7个线程。只需将它们组合在一个可运行的
中,事情就会简单得多。
我的意思是,您所有的
/**延迟等待…*/
注释都是错误的,您在上一个操作开始后等待了1秒。因此,在“发送请求字符串以读取第二个值”之前,您没有完成“接收第一个值”,因为这花费了超过1秒的时间。

示例:
您的代码已简化:

private Handler read1_handler = new Handler();
private Handler write2_handler = new Handler();
private Handler read2_handler = new Handler();

public void receiveValues() {
  /**Delay to wait until it receives the answer to the petition above*/
    read1_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            String inpuRead = "2b 00 ff fe c7 80";  //This string is what I receive as an answer via bluetooth
            if (inpuRead != null) { //|| !inpuRead.equals("")) {
                int splitInt = splitReceivedString (inpuRead);
                receive1 = splitInt;
                Toast.makeText(getApplicationContext(), "Loading values", Toast.LENGTH_LONG).show();
            }
            else {
                Toast.makeText(getApplicationContext(), "Communication error", Toast.LENGTH_SHORT).show();
            }
        }
    }, 1000);

    /**Delay to wait to send de second petition string*/
    write2_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            byte[] send2 = message_full2.getBytes();
            GlobalVar.mTransmission.write(send2);
        }
    }, 2000);

    /**Delay to wait until it receives the answer to the second petition string*/
    read2_handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            String inpuRead = "2b 00 ff fe c7 80";
            if (inpuRead != null) {
                int splitInt = splitReceivedString (inpuRead);
                receive2 = splitInt;
            }
            else {
                Toast.makeText(getApplicationContext(), Communication error, Toast.LENGTH_SHORT).show();
            }
        }
    }, 3000);
}
具有正确执行顺序的代码:

private Handler handler = new Handler();

//TODO: don't call functions read1, write2 etc, call it something like "readSomeValue" where "SomeValue" is what you're trying to read
private void read1() throws IOException {
    String inpuRead = "2b 00 ff fe c7 80";  //This string is what I receive as an answer via bluetooth
    if (inpuRead != null) { //|| !inpuRead.equals("")) {
        int splitInt = splitReceivedString (inpuRead);
        receive1 = splitInt;
        Toast.makeText(getApplicationContext(), "Loading values", Toast.LENGTH_LONG).show();
    }
    else {
        throw new IOException("Error in read1");
    }
}

private void write2() {
    byte[] send2 = message_full2.getBytes();
    GlobalVar.mTransmission.write(send2);
}

private void read2() throws IOException {
    String inpuRead = "2b 00 ff fe c7 80";
    if (inpuRead != null) {
        int splitInt = splitReceivedString (inpuRead);
        receive2 = splitInt;
    }
    else {
        throw new IOException("Error in read2");
    }
}

public void receiveValues() {
    handler.post(new Runnable() {
        @Override
        public void run() {
            try {
                read1();
                read2();
                read3();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "Communication error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    });
}

对我来说,看起来你可以使用循环barier,依靠一些神奇的延迟是令人难以置信的

或者可能:


这个问题似乎离题了,因为它是关于代码重构的。他确实说它有时会崩溃,这表明存在问题,但他没有说明任何细节。@Ruchira抱歉,我不知道你说的代码折射器是什么意思。我不知道我该问些什么,我只是想寻求一些帮助,因为我知道这里有很多人对android非常了解,他们可以快速向我展示如何正确完成这项工作的示例。如果你不知道什么是代码重构,请查阅。简单地说,它意味着在不改变行为的情况下“清理代码”。这不是为什么,关于这个问题有很多书。您提出的问题应该与实际的技术问题(即它崩溃)相关,但您应该提供适当的信息(异常、日志输出等)@Ingo Bürk首先,我知道结构不正确,因为如果一个if不正确,它会转到另一个显示“通信错误”的toast,我希望代码停止执行,但这样它会继续执行,我不知道怎么做。另一件事是,有时我一次没有得到收到的字符串,它一次发送两个请求字符串,而没有先得到收到的字符串,这是如何做到的?我的意思是,我知道runnable中的代码是在设定的时间之后执行的。所以这里面的所有代码都会在1秒后执行。。。那么,如何在1个可运行的内部轮流执行7个任务???@masmic_87,为了更清晰,我编辑了我的答案。为什么您认为1秒是完成上一个操作所需的时间?如果您只是将
Runnable
s中的所有代码复制粘贴到其中一个,然后删除其他代码,会怎么样?(当然,如果你能为每个任务创建方法,并以仅可运行的方式调用它,那会更好。)好吧,我从连接PCB的计算机上看到所有发送和接收的字符串,我决定设置1秒作为等待时间,但你是对的,有时当它出错时,确定这是因为正如您所说,在开始发送第二个请求之前,它还没有完成第一个值的接收。另一方面,我理解您所说的只在一个runnable中设置所有代码,并为每个任务创建方法,但我不知道如何做到这一点。你能用一个简单的例子来编辑你的答案吗?谢谢谢谢@spongebfan!但是在这种情况下如何实现异常呢?很抱歉问了这么多,但我从这个开始,我还有很多事情要做learn@masmic_87,我已经编辑了我的答案。当其中一个方法引发异常时,
try
中的代码将停止执行,然后执行
catch
块。
catch
块只有在异常出现时才执行好的答案,
java.util.concurrent
肯定会有帮助,但我不认为有理由让事情变得如此复杂,如果你只是想通过turnah完成一些任务,他只是快速查看了一下,所以OP不知道读取可以是阻塞操作,所以代码可以在他完成接收后执行。