I'm reading Sensor Data from Device Sensors(Multiple Sensors) and call a Method to show the data I received from sensors to the designed TextView.
The method I'm calling to update TextView:
private void UpdateDataStream(String _Entry,Boolean isAppend)
{
if(isAppend)
ViewHolder.append("\n("+sensorName+")"+_Entry);
else
ViewHolder.setText("("+sensorName+")"+_Entry);
}
Method called from SensorEventListener's , onSensorChanged Event.
What I couldn't figure out is how to prevent freeze while updating TextView; since sensor data update is intensive(considering it is from multiple sensors simultaneously) updating TextView cause Application to freeze or crash. I don't need to "print" every data I received, like It is enough for me to print for every 1-2 second, lost data can be ignored.
Is there any approach/patern or built-in structure to achieve this ?
(I'm new to programming in Java&Android, yet I'm familiar with multiprogramming, parallel programming concepts, yet I couldn't figure out how to apply them in this environment)
This is fastest solution:
https://github.com/ReactiveX/RxJava
http://reactivex.io/documentation/operators/debounce.html
Or you can:
create stack (for example)
write sensors data stream to stack from thread#1
in another infinite loop thread#2 read last data from stack every N time (don't forget to synchronize them)
clean the stack
write last data to TextView (don't forget to set text in ui thread: textView.post( () -> textView.setText("safe call") );
Related
I'm building an app that will read sensor data and store it into kafka with rest controller as middleman. (First time working with sensors)
UI consists of Sensor name + switch button to start or stop sending sensor data.
I'm trying to regulate how much of sensor data is send, because my android app just cant keep up with some of the sensors when they start with sending data, my UI just blocks.
I was testing with Emulator and sensors that have goldfish in there name, they work normally, Game rotation vector sensor, gravity sensor, and few others just start sending to much of data and app cant keep up.
(I'm sending data with new thread each time).
SensorManager.registerListener(sensorEventListener,sensor,500000000);
Changing samplingPeriod just didnt help at all, some sensors work normally and some just keep sending to much of data regardless of number.
I tried that, with each sensor change event, new Thread starts with sending data, so that UI would work normally, but my app cant keep up with some of the sensors.
public void onSensorChanged(SensorEvent sensorEvent) {
Thread t = new Thread(new MyOwnRunnableClass(sensorEvent,username));
t.start();
}
Make a native app to learn sensor
Don't create a thread every time a sensor updates because every thread generates over head. You want one thread to manage the sensors, one for ui. Should be enough.
Your sensor thread can drop readings if there are too many for your need (just process one out of ten)
Sampling rate used to work more or less when I used to develop in android native.
Read tutorials, using sensors is key in mobile so every framework has tutorials on how to do it the right way
Good luck
second way:
you can set previous time in shared preferences and in OnSensorChanged method check if difference of current time and last time is over than 500000 set your data.
first way:
you can use alarm manager to do this every 500000 s;
I'm developing a "chat" app that retrieves some data (the messages) from a database (firebase real-time database), does some manipulations and then populates a listview in order to display them on the screen. I have 2 types of messages:
The first type is text messages, the manipulations on them are very short and don't take a long.
The second type is pictures. The manipulations on them are longer than on text (few seconds).
When the activity starts, the app retrieves all the messages from the database, and has to do the manipulations on each one of them (text and pictures). Before we see anything on the screen, it has to finish the manipulations on all the messages and then it takes a lot of time.
My question is: is there a way to populate each item in a different thread? Like to see on the screen the text messages appear (because the manipulations on them are fast) and then the pictures when each one of them finish at its own time (same idea like a website when we see the text before all the pictures finish to be loaded). Of course the messages need to appear in the same order like they were in the database (actually I retrieve them with the onChildAdded() function).
I really hope it was clear, and if not I will be happy to clarify any point.
Thanks everyone!!!
Define them as different Threads:
[...]recive messages
if (/*message an image?*/) {
new Thread(() -> {
//Do something
}).start();
} else {
new Thread(() -> {
//Do something else
}).start();
}
Hey guys:) I'm currently working on an android project, where I want to realize a chat function. I know there are several tutorials which describe a chat app but I want to do it myself with my own Server.
In my MainActivity I start a self written updater in a new thread (bc. of network-operations can only be done outside the UI thread), which permanently checks, if the chat-protocol, which is stored on my server (RaspberryPi), has new messages from other users. If there are new messages, the Updater downloads it and stores it in a string. This works fine!
Now, when the updater receives a new message, I want to update the ListView in my Chat-Activity with the new message. This process should work at any time and update my ListView permanently (not with a refresh button or sth. like that).
My question is: how do i realize this the smoothest way - a strategy, not necessarily code. One idea, which works but feels a bit random, is to write the received messages in a shared preferences-file and load it in the chat-acivity via an infinite loop in the chat activity.
Is there a possibility to write the received messages directly in the ListView at any time from the thread with the updater which was startet in the MainActivity.
If needed i could upload the current code but i want to do it directly and not with an infinite loop.
Thanks for reading and maybe even for the help :)
You may want to save the received messages in SQLite database, and inside the activity, you can poll the database (suppose for every 5 seconds) and stop polling after the activity is destroyed.
Another way would be to use the static references of the views and update them from a different class. Even you are trying to update them from inside a background thread, you can update the UI using view.post()
SomeActivity.textView.post(new Runnable(){
#Override
public void run(){
SomeActivity.textView.setText("sth");
}
});
My code retrieving on AsyncTask data from cloud database.
I have notice, if I am putting break point(while debugging), My code runs ok, the data received and then my code manipulate that data.
If I am not using any break point my array is null, the code did not wait for the data to arrive.
I have tried,
Thread.sleep(timeInMills);
and
SystemClock.sleep(timeInMills);
but this did not help, It seems to stop the entire Thread.
Is there a way for me to stop the code the same way break point does for a second or two.
Again this does not effect my UI Thread as this run in AsyncTask.
i have faced a similar situation
if you send the result array to an adapter or a function make it execute at the end of onPostExecute method , as before that your data Array would be empty
I have a sync service using AsyncTask. Due to its objective (sync), I prefer to block the user and show him a progressdialog. (And error if exists)
Another difficulty is that I have about 8 AsyncTask running simultaneously. So I can't do a simple call to the progress dialog page when I begin the work and a close when it's finished. It's more complex.
Can someone help me with that task ?
Regards
onPreExecute(), onProgressUpdate(Progress...) and onPostExecute(Result) in AsyncTask are invoked on the UI thread. You can use these to display a progress bar, update it as the syncing progresses and hiding it when the work is finished.
As to the 8 simultaneous async tasks, do you really need 8 concurrent tasks? Can't you run them sequentially on one background thread using a single AsyncTask?
In the first place the point of the Service is that you don't need/want to block user to do stuff because it happens in the background. To that aspect, a Service doesn't have a UI thread, so if you want a progress bar shown in your Activity you'll have to send an Intent back to your activity (using broadcast receivers), such that you can switch the progress bar on/off and do other magic.
I would not recommend blocking the user though, because the tasks you are doing might take a very long time, giving a nasty user experience. You might even want to reconsider using a Service at all (if the data you are fetching is only used locally; for example fetch the latest twitter messages or something) and just go with an ASyncTask in your Activity, unless the data your Service fetches is used in other parts of your app as well (widgets for example) and you want that data available even if the activity isn't running.
You can make use of progress dialog to show wait cursor kinda thing.
Also you can imitate the concept of CountDownLatch in your application to dismiss the cursor. Like you can have a static function in a class like updateTaskComplete and update a static counter. And once the counter is equal to number of async task then in the function updateTaskComplete cancel the progress cursor. I mean you have to do something on this line.