I've been developing a few basic Android apps recently and notice a slightly odd behaviour which I'm sure is my own wrong doing.
The problem seems to lie with the main thread which I'm using for both updating the UI and some processing such as sending a message via Bluetooth.
Let's say I have the following:
public void sendMessage(){
updateUI();
sendBtMessage();
}
public void updateUI(){
txtView.setText("Sending message");
progressbar.setVisibility(View.VISIBLE);
}
public void sendBTmessage(){
... connect to BT and send message here
}
As I run my code it appears to be running sendBtMessage first as the UI update appears after the message is sent(I would like it before sending the message). Is this because the main threads priority is to do the heaviest work-load first?
Should the main thread be used for only updating the UI?
Any Suggestions or advice would be appreciated.
Turns out I needed to handle the sendBTMessage on a new thread such as:
new Thread(new Runnable() {
public void run(){
...processing
}
}).start();
and the UI runs smoothly using
RunOnUiThread(Runnable)
Related
This is my first Android application and I am finding troubles with while loop, I am trying to use a while loop on my Android application but the application freezes.
What I'm trying to do is track the user location (using onlocationChanged) and keep querying on the location until the query returns a result. It's a GIS application so I am going to describe the application behavior:
the application keeps tracking the user position using a listener "onLocationChangedListener" and store it in a variable "myPosition". I am using a boolean"noResults=true". I will use a method "query(myPosition)" in the while loop, this method has a callback that when a result is found, and changes a boolean "noResults" to false. the loop will keep on until "noResults" is false (that means query's callback changed the boolean's value)
, here's what I did:
while(noResults)
{
//myPosition keeps changing
query(myPosition);
//query has a callback that when a result is found it changes noResults to false
}
I resolved the problem using a "Handler" that query the Feature Layer every 5 seconds, this stops the main thread from generating application not responding error:
Handler m_handler=new Handler();
Runnable m_runnable;
m_runnable = new Runnable(){
public void run() {
//query code here
m_handler.postDelayed(m_runnable, 5000);
}
};
m_handler.postDelayed(m_runnable, 0);
running while loop codes on the main thread freezes the UI, and makes all other processes pause making your app unresponsive use
Threads..
also note that the while loop you are running is running on a default Thread termed as the ui thread so in short run while loops on separate threads..
eg..
new Thread(new Runnable() {
#Override
public void run() {
// Your hard while loop here
//get whatever you want and update your ui with ui communication methods.
}
).start();
for ui communicating methods
View.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "updated ui", Toast.LENGTH_LONG).show();
}
});
the view could be any views you are updating..
also like #TehCoder said you could use asynctask but asynctask is not meant for long workaflow work there are 3 of them but i can't recall the last one
Maybe you should use an AsyncTask? I'm not quite sure what your problem is tho.
Loop is not a problem in android (or any language).
There are two scenario might be reason for your freezing,
If you run network call in api, android throw error and crashes. You have to do network related calls in Aysnc Task ot threading
Use try throw catch and exception cases to avoid app crashing and better coding skill.
After discovering that Google redesigned the threading model in AsyncTask which now comes with a major bug of blocking code, I've chosen to abandon using the AsyncTask and simply use Threads and Runnables, so please don't post any comments on AsyncTask as that is not my discussion. What I would like to know is whether the following is the correct way to implement a nested Runnable that runs stuff on the UI thread:
private class MyOuterRunnable implements Runnable
{
#Override
public void run()
{
int x = 1;
// Do something on the UI thread.
runOnUiThread(new Runnable()
{
public void run()
{
// Update a listview, etc.
}
});
}
}
For the most part, this seems to work, but I am experiencing crashes in certain modules where I do it this way. Is this the proper way to execute UI stuff from within a nested Runnable or should I be doing it differently? All LogCat tells me is that a fatal error occurred in the nested runnable but doesn't provide any detailed info.
I have to receive an image via socket and display it in a ImageView .
But after ui updation socket get disconnected .For ui updation i use Handler ,i also tried Asynctask. socket running in Thread.
How to remain connected to socket while updating ui simultaneously
The image updating should be done via runOnUiThread:
runOnUiThread(new Runnable() {
public void run() {
if (isrunning) {
_tts.speak(num,TextToSpeech.QUEUE_FLUSH, null);
}
}
});
If you post some code, I could update the answer.
I'm new to Android. In my current project I'm using the asmack library to receive XMPP messages. In my MainActivity I have:
Connection connection; // from the asmack library
and
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
// HERE! is where I want to update the UI when I receive packets
}
}
The weird thing is when I parse the packet and simply call setText() on two labels. At first nothing happens, but when I touch a Button (hence calling some update routine) only the first label is updated.
Now, as far as I understood you're supposed to use AsyncTask in such cases but this didn't work out either.
Did I misunderstood some core concept? Can someone lead me to the right path?
The packet seems to be processed on a separate thread than the UI thread, which means the UI will not be updated immediately since you're not manipulating it on its thread. Therefore, you should do something like this...
connection.addPacketListener(new PacketListener(){
public void processPacket(Packet packet){
//update the UI on its thread
runOnUiThread(new Runnable()){
public void run(){
//update UI elements
}
}
}
}
When I want to connect to server I got ANR message , some solution is to use Thread concept . The following is my code and the app show force close message. Is there something missing in my code
public void theardupload()
{
new Thread() {
public void run() {
ConnectToServer(url);
}
}.start();
}
Look at Lalit's answer in Android thread not working
Also you must make sure that all exceptions are handled in your ConnectToServer function otherwise the thread will cause an unhandled exception and force close your app