New to stackoverflow, been very helpful searching, but alas the time has come to ask a question.
I am trying to use an android 2.2 single core phone to do some research. I have implemented an algorithm that does quite a few calculations and produces a lot of data. These data must be processed, and the solution presented back to a client app within a 40ms time frame, then process again with new state data coming from the client. Also, the result of the calculations must be stored to the SD card as a data log. So being new to multithreading and android both, what should I use to do the following in my app: (As a side note, this phone, when in research mode is not intended to be used as a phone, phone will be in airplane mode with wireless off, and all apps that can be turned off will be turned off, and there is no need for UI display or interaction once it is up and running...)
need to process packets coming in over adb on serial port, these packets are state data that the program needs to perform its calcs on. These packets will be coming every 40ms, so I planned on using their arrival to trigger the start of the processing.
need to know if the algorithm is taking longer than 40ms and cancel it if so and send a message back on the serial port that it overran.
the calculation results need to be sent back over the serial connection via tcp and adb
The calculation intermediate data need to be recorded to SD. This can be quite a lot of data, on order of 140k, every 40ms.
So I have had trouble getting all the pieces together. I can't get my head around how a single core is going to keep up with all this going on at once?
So here is my thought, please tell me if I am headed in the right path. I am not asking for you to solve my problem, only any advice on how to break this beast down:
So i start a service to process the tcp packets coming in from the client
Use a service bound to the main worker thread to handle writes to the SD card
So assuming this setup, can i make the algorithm part of this somewhat deterministic so that it always runs if it gets a new tcp packet, and preempts the SD write going on in the background?
Argh...should have picked something simpler for my first program
Thanks.
Yes I think you are right, that it would be better to pick something easier for your first App ;)
But as far as I understand what you are trying to do, I don't think, that you need asynchronous multiprocessing. You get some data want to process it and pass a result. I think a HandlerThread is exactly what you are looking for. It is able to recieve Messages
with data inside. You send them to the Handler and process them in an overridden handleMessage(Message m) method. So everytime you recive a Message you could just log the Time
and see if the last one is older than your limit. If it is, you could just throw the Message or the whole queue, or send a Message to your serial-port inicating the overflow.
This could be implemented as you suggest in a Service. Another HandlerThread can be started with Thread.PRIORITY_BACKGROUND to write everything to SD.
You can send Messages even very compfortable if you apply a Messenger to the Handlers
Related
I have a scenario which I need to resolve. Currently I'm able to connect to an embedded system through socket connection, via android device.
I was able to use asynctask to send xml commands and receive them back, update UI with the results. But on the last step I need to use a command which will start the system to work, and I will keep getting messages from the system. it will be sent variously and the time can be different (we are talking about few 200-500 ms).
So my question is:
Asynctask wouldn't work. Because the 'work' varies more than 100ms and I'm not sure when the messages will be send, So I can't use async and show dialog for unknown time.
I have read that intent-service or service can do this work, but I'm not sure yet if it will be a good solution.
What would be a good solution for receiving these messages and for updating the UI?
I have built an Android chat application. It has a TCP server which is connected to via using a Socket.
I want the server connection to work in the background always - even if the app is not in foreground - and listen to data sent from the server.
For now I am using a while loop to checking if there is something new, but the OS close my thread when Android needs resources.
I have thought about using the readline() method in my thread instead of using the while loop because readline() is a blocking method.
Is this the right approach to take, which will lead to, prevention of the OS from killing my application?
Is there any way, like a custom broadcast receiver that will launch only when the incoming socket is available?
Thanks!
In short, Android can and will kill any applications that hog up resources in order to keep running. The onus is on you on how to handle the scenarios which can threaten your app to be killed.
I suggest looking at the service's life-cycle as found on the developer's site.
For a start, any application, be it service/activity, that hogs up too much, in this manner is considered... "rude" in the eyes of Android, and therefore, is prepared to be killed in this manner regardless!
For example, listen in the onLowMemory override method and act accordingly, such as saving data and what-nots.
What really, should be happening, is this, the service, spawns a thread to periodically listen for incoming connections in this manner,
while (!terminating){
Socket incomingClientSocket = ourServerSocket.accept();
// How you handle this part is up to you?
Thread.sleep(500); // Sleep for 500 ms
}
The terminating variable is a boolean and is the deciding variable that controls when to terminate the loop. Notice how the Thread.sleep method is used, to "calm down" the execution, if omitted, Android will put a cross-hair on the app and terminate it, in other words, be polite to system resources.
Hint: Extend the Thread class, to hold the functionality of handling incoming connections via the accept() method.
When the incomingClientSocket becomes non-null, then another thread is created in which it opens the input/output stream of the incomingClientSocket and read/write to it using binary fashion.
Do not use the readline method as that is an indication of poor design and assuming the data is text-ual, because one incoming packet to the client could be for example, 720bytes, the next packet coming in after that, could well be 564 bytes, that is the nature of TCP/IP.
You need to come up with a more reliable way of establishing boundaries for the data transmission, for example, a begin and end marker, and let the server read the incoming data and distinguish the byte stream that composes of a begin and end markers, once both are present, then extract the real data in-between the markers and act on it accordingly.
You could for instance, say, upon incomingClientSocket that actually becomes non-null, send a broadcast to your activity to act on it, and let the activity, take that socket, and open the connection and read/write to/from the input/output streams associated with the socket.
I am creating a simple android game that deals with multiplayer and connecting to server. This is what I want to achieve for my game.
Client sends keystroke movement to server.
Server accepts input, update the state and calculates and returns new position to client
Client gets new position and update the screen.
I already have some code written and so my one of my threads sends keystroke to server, waits for the new position, then update the screen. The thing is there is lag between the player's movement. I think it has to do with latency. I also tried two thread, one for sending/receiving data from server and another is updating the screen. But it didnt' solve my latency problem.
Can anyone suggest a good design for networking game?
Do I need to do early prediction?
Do I need separate thread for fetching data and rendering screen?
P.S.This is my first time creating a network game so i have no idea what im doing.
The structure I prefer to use is to have one thread updating graphics and logic on the client side, and then one thread receiving and sending data to the server. If you have problems with latency, there is a magic option which might solve it if you want data to be sent continously. (at least this is the syntax if you are using java)
mySocket.setTcpNoDelay(true);
This option solved my latency issues when I sent real-time coordinates over a network.
Edit: I think TCP by default waits and bunches together data before sending it, which could be a problem if you want to send small updates fast.
I have been doing some research lately over my work project, i am trying to read card swipe data from Bluetooth card reader in my app.
So as to get that data i have to use thread, i know the reason why is there a need to use so as this process does not hinder interface activity, but here my concern is not to handle interface activity at the time of fetching data. But threading makes sense when there is a need of BluetoothServerSocket so as to have full duplex connection.
So my question basically is that if i am just receiving data from remote device do i really need to have a BluetoothServerSocker under Thread?
When you are doing some action that is going to take some time in performance, then it is better to use Thread. When you are reading Data from Bluetooth Card Reader, then in this case, in background many activities take place. for e.g. Bluetooth Connection, Device Discovery, Pairing, Asking for permission , retrieving data. It may be possible cause of device hang or user may not like to be in wait state. so to prevent such cases it is better to use Thread.
I've asked various questions related to one goal: how to develop an Android app that plots bluetooth data forever in real-time. I now have a new question from a different angle. To be fair to new readers I will cover some of the same background, but basically the question is in the title.
I found some open source code Bluetooth that apparently creates a background thread which updates the screen with new data it receives over a bluetooth connection. Then when I launch my Plot activity I can see the bluetooth background thread continue to write bluetooth data to Logcat. So I know for a fact the bluetooth background thread is still running when I launch my Plot activity.
Again, my goal is to plot the bluetooth data that is continually provided by the bluetooth background thread. I have succeeded as follows: since this bluetooth background thread seems to run continually and just won't die, I decided to use its update() method to call my static Plot.plotData() method to plot the data. And this works. It will will run endlessly with out a problem - receiving bluetooth data and plotting it via periodic calls from the bluetooth background method update() to my static Plot.plotData() method.
Although I have received some negative feedback regarding my solution, I have found sharing data across Activities where Edward Falk says sharing static data is OK. Here Edward Falk asks: "Are the activities all in the same application? [yes] Same task? [not sure] It seems to me that you could just store the data in a static variable accessible by all of the activities." Well I tried static data and it worked, but I switched to a static method Plot.plotData() which seems to work better for me.
The latest feedback I have received from one person #emmby that says my static Plot.plotData() goes against the following: "It sounds like you're looking for an in-memory way to share data, and that's simply not the way the Android activity model works." But what am I else to do? I thought that an Android phone has a limited amount of RAM for running Activities (one at a time), threads, handlers, Services, AnycTasks, etc. And an SD card for persisting data.
#emmby seem to say that in order to share data from a bluetooth background thread to my Plot activity (Plot.plotData()) that I must use the SD card. This doesn't sound right. After all I have it working using my static method Plot.plotData().
Frankly I don't see anything wrong with my solution primary because those who criticize it do not follow up with a definitive alternative.
If you find my solution deficient please speak up and provide a definitive solution. Otherwise I will take Edward Faulk's solution as the best one.
If I understood you correctly, your thread is running at the background even when none of the activities display data obtained by that thread. For example, let's consider scenario:
You started your bluetooth thread.
Your activity A started and now read data from that thread.
Your activity A is backgrounded (for example user navigates away via "Recent" tasks).
Your activity is idle but bluetooth thread still consumes cpu and power.
If you don't use your bluetooth data you shouldn't run the thread. You can introduce some kind of counter that tracks number of clients that use your thread's data. And if counter drops to zero - thread stops/pauses.
But Android has built-in solution for such cases. You can introduce service which will be bound by different activities and will have DataSource interface with getNextData function. See Bounded Services for more details.
When there are no clients bound to service Android will stop the service. This way you completely decouple Activities from thread. Your bluetooth thread is now managed by Service. And Service is now managed by Android.
In your case Local Service should be enough to share data between your thread and activities.