how to Run socket and ui updation simultaneously without interruption - android

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.

Related

Alternative for retrieving Data From WebServices Using AyncTasks

I have an Android application that uses AsyncTasks to make get and post calls to send and retrieve data from server. All works fine but sometimes the async task takes a lot of time to execute and thus other async tasks have to wait (if more than 5 async tasks is there) so what will be the best alternative or how to increase the thread pool if it is safe to do so.
Asynctask are implemented behind the scene using threadpool, the default pool size for asynctasks is 1(so you can't run 2 asynctasks in parallel).
In newer versions of android the default Asynctask pool size is 5.
It's possible to change it but not recommended.
You can just create thread like in the sample I attached before:
Thread thread = new Thread() {
#Override
public void run() {
try {
//Do http request here
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();

Android: Thread infinite loop / phone overheating

I'm working on a Thread that handles all server connections:
public void run() {
//this initializes Socket and PrintWriter/DataInputStream
connect(server, port);
while(true) {
//queue is a BlockingQueue where I put the messages to send
while(!queue.isEmpty()) s
//COMMUNICATE-WITH-SERVER-CODE
}
}
}
The code works, but after a minute or so, my phone starts overheating and battery goes down fast. I know it's because of the infinite loop.
How can I solve it? I want a Thread which, once started, keeps the connection to the server (so that DataInputStream and PrintWriter won't be initialized every time). And I want the thread to be responsive: when I click a Button it should sent instantaneously a message to the server for processing.
I have implemented a Handler for communicating Thread->Activity. But how can I communicate Activity->Thread?
Any tip would be welcome.
Generally the solution would be to add a polling intervall, ex: sleep the thread for 500ms after each iteration. But in this case there is no need for that, because we do not have to poll a BlockingQueue. From the doc
A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
If we use a BlockingQueue, then the queue.pop() call blocks if the queue is empty and remains blocked until an entry is pushed onto the queue. There fore there is no need for looping.
However, we will need to have some sort of mechanism to keep the thread from terminating. Here is a simple example:
public void run() {
try {
while (true) {
handleServerIO(queue.take());
}
}catch (InterruptedException ex) {
... handle ...
}
}

UI thread issue

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)

android.os.NetworkOnMainThreadException, while NOT actually running in MainThread

There are many previous questions regarding the android.os.NetworkOnMainThreadException exception , which is essentially a protective approach by android to prevent us from freezing UI.
Opening a socket from another thread (hence, not the MainThread) should solve this issue:
Thread t = new Thread (new Runnable() {
#Override
public void run() {
try{
Socket socket = new Socket ( SOME_IP_AS_STRING , SOME_PORT_AS_INT);
// do some IO with socket
}
catch (Exception e) {}
}
});
t.run();
However, this code throws the mentioned exception - android.os.NetworkOnMainThreadException,
and when debugging (using the Android Studio), it looks like run() is running under the MainThread after all, which makes no sense.
where do I got it wrong?
You're calling .run() which actually will run the Thread in your main UI Thread. You need to call .start() instead to avoid it.
The exception that is thrown when an application attempts to perform a networking operation on its main thread. Try to run your code in AsyncTask , For more detail refer here

Updating UI when XMPP message arrived

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
}
}
}
}

Categories

Resources