'How Use Timer Inside onMessageReceived()

How to use Timer Inside onMessageReceived(), originally if I did not use the timer I will get 30 date data for 1sec, but I want to collect 50 date data for 1 sec. So I need to use a timer to get more data. but if I use a timer the App will be force close. how to solve it or any other way to get more data in 1 sec based on the code below:

            private void onMessageReceived(String message) {
            //store incoming bytes temporarily
            if(!is_L_insole_started){
                left_temp_bytes+=message+" ";
            }
            //check whether the start_bytes exits in the temporary buffer
            if(!is_L_insole_started && left_temp_bytes.contains(start_bytes)){
                is_L_insole_started = true;
                left_temp_bytes ="";
            }
            //if the start_bytes are found in the temporary buffer, start storing the incoming messages in the actual buffer
            if(is_L_insole_started){
                left_data_len++;
                if(left_data_len>15) {
                    left_sensor_data_count++;
                    if (!non_sensor_indeces.contains(left_sensor_data_count)) {
                        l_data_double_arr[left_data_index] = Double.parseDouble(message);
                        left_data_index++;
                    }
                }

                //if the data length reach the max_data_length, release the buffer and invert the start flag
                if(left_data_len>=max_data_len+15){
                    heatMapLeft.clearData();
                    for(int i=0; i<x_L.length; i++) {
                        HeatMap.DataPoint point =  new HeatMap.DataPoint(x_L[i], y[i], l_data_double_arr[i]);
                        heatMapLeft.addData(point);
                        heatMapLeft.forceRefresh();
                    }

                    left_timer = new Timer();
                    left_timer.scheduleAtFixedRate(new TimerTask() {
                        @Override
                        public void run() {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    // update UI here
                                    Date date = new Date();

                                    test(String.valueOf(formatter.format(date)));
                                }
                            });
                        }
                    },15, 20);

                    left_package_count++;
                    left_data_index= 0;
                    left_sensor_data_count = 0;
                    left_data_len=0;
                    is_L_insole_started=false;
                }
            }
        }

    public void test(String date){
    Log.d(TAG, "jembatan: " + date);
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source