1

For now my app have a chat that comunicate via bluetooth with an OBD port in the car.

Now i want upgrade my project for real time information, so i want create a method that repeat some Array with a list of commands and repeat the sendMessage(message) every sec or 500 millisec (something for real time data).

There is some bestway to do that?

I have my Activity with 4 EditText for showing data and a Button with "start scan" and if pressed it becomes a "stop scan" and interrupt the infinite loop of commands.

In the same time i need to take back data and show results in the EditText.

EDIT

Or just use an AlarmManager?

EDIT 2

With this code not work properly because send only the first message after 5 sec and the second it lost... How can i send all the commands into ArrayList one at a time every t millisec?

public void repeatCommand(){


        for (final String command : commandArray){

            final Handler handlerTimed = new Handler();
            handlerTimed.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //Do something after 100ms
                    sendMessage(command);
                }
            }, 5000);


        }

        /*String message = "010C\r";
        sendMessage(message);*/
    }
Community
  • 1
  • 1
Dario
  • 732
  • 7
  • 30

1 Answers1

0

Sorry I didn't write android code for so long but I had your case so long ago.

You have to define a Service and start it in foreground with RETURN_STICKY and then write a handler with timer which execute your code per second (or what you like!). Then you can broadcast your result or how you want to communicate with your activity and use it.

Then start service and stop it with your button.

PS: 1. As far as I know alarmManager is not a good idea in this case.

  1. Somehow you have to be sure that your Service will not be killed by android.
mohsen_og
  • 774
  • 1
  • 9
  • 31
  • So with the Service i manage the data exchange and when take back data from obd i send the results (maybe formatted to human readable results) to the activity and take it back with broadcast? Someone (or you) can help with some code? – Dario May 17 '17 at 20:43
  • 1
    hey, I don't have any code right now. I will write some code here tomorrow. Anyways, as I said all the OBD communications must be in a Service. OBD-Servic should get the OBD data and broadcast them (or even you can define a interface and do it without broadcast!). Then any activity that needs those data can get the broadcast. regards, – mohsen_og May 19 '17 at 08:01
  • I update question with some code...but not work as i think – Dario May 25 '17 at 15:40