从处理程序获取字符串数据以更改电池图像

时间:2018-05-09 15:02:36

标签: android

我的项目有问题。我被困了,因为我无法从Handler取出我的字符串,因为Handler消除了数据。我是新手,我从https://gist.github.com/ashebby/db63b0db7489d604841a获得了Handler代码。我的问题是我的Android应用程序正在获取有关我的设备电池的百分比数据,但由于处理程序不断擦除字符串,因此无法更改我的ImageResource。有没有办法存储字符串?如果我的处理程序得到了新的字符串但没有删除它会更新吗?

这是我的代码:

 bluetoothIn = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == handlerState) {                                     //if message is what we want
            String readMessage = (String) msg.obj;                                                                // msg.arg1 = bytes from connect thread
            recDataString.append(readMessage);                                      //keep appending to string until ~
            int endOfLineIndex = recDataString.indexOf("~");                    // determine the end-of-line
            if (endOfLineIndex > 0) {                                           // make sure there data before ~
                String dataInPrint = recDataString.substring(0, endOfLineIndex);    // extract string
                myLabel3.setText("Data Received = " + dataInPrint);

                if (recDataString.charAt(0) == '#')                             //if it starts with # we know it is what we are looking for
                {
                    String readBat = recDataString.substring(1, 3);             //get sensor value from string between indices 1-5
                    //myLabel2.setText(" Tegangan Batre = " + sensor0 + "V");   //update the textviews with sensor values
                    myLabel2.setText(bacaBat);
                    //String bacaPercentage = bacaBat.substring(2,3);

                    if (readBat == "50"){
                        batt.setImageResource(R.drawable.bath_50);
                    } else
                    if (readBat == "25"){
                        batt.setImageResource(R.drawable.bath_25);
                    } else
                    if (readBat == "0"){
                        batt.setImageResource(R.drawable.bath_0);
                    } else
                    if (readBat == "100"){
                        batt.setImageResource(R.drawable.bath_100);
                    }
                }

                if (recDataString.charAt(0) == '*')                             //if it starts with # we know it is what we are looking for
                {
                    String bacaPD = recDataString.substring(1, 10);             //get sensor value from string between indices 1-5
                    //myLabel.setText(" Hasil Bacaan Photodiode = " + sensor1 + "V");
                    myLabel.setText(bacaPD);
                }

                recDataString.delete(0, recDataString.length());                    //clear all string data
                // strIncom =" ";
                dataInPrint = " ";
            }
        }
    }
};

0 个答案:

没有答案