What is the right way to get an integer value back and forth between threads?
I have two threads running a run(){} function. One is receiving/sending USB messages and one is running a game UI. They both work independently. Modifying the value of the game with the data from the USB is the problem area.
What I’ve tried so far: I tried creating a global object called container which contained a public int variable and passing that to both the threads to communicate, but it crashes the program upon running.
Edit: Can I save the file to the SD card and have the other thread view it? Thread 1 will need to write to the SD card and thread 2 will need to read it. There is no need for two way comm.
edit: If there’s a way to create an application wide, global variable of type int, or an application wide object containing an int, that will work. If doing that exists, I’d like to do it that way.
You should probably stick to the Android threading model. See this for example.
The UI thread is the main thread in Android. If your UI thread is not the main thread, you did something wrong.
From the link above, don’t use AsyncTask since you need something that modifies the UI more than once (I presume). Call instead
from your thread that reads USB. When you declare that Runnable you’ll need to have
someUIElementandsomeIntReadFromUSBin the scope. If they are local variables in that scope, you’ll have to make sure they arefinalvariables. (If you do have to declare the integer final, you can just declare a new final variable right before you define the Runnable and copy the value you want to send to it.)