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
Related
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();
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.
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)
I have some code that will not run if I don't have a breakpoint. My speculation is that the code gets executed too quickly, and the time between me allowing a breakpoint to continue lets a thread lock on to my code. It also doesn't get "caught" with my exception handling, so its not bad code, but when the breakpoint is there it will dive into the try further and do everything I want it to do
not sure how to get this to work without being in debug mode! I am considering wait() or sleep() functions but it seems like a silly workaround, let me know if there is a better way
Thread triggerService = new Thread(new Runnable(){
public void run(){
Looper.prepare();
try{
// ....... code here does not get executed
// such as if statements or anything
Looper.loop();
}catch(Exception ex){
System.out.println("Exception in triggerService Thread -- "+ex);
}//end catch
}//end run
}, "myNewThread");
triggerService.start();
Insight appreciated!
Code works fine for me. Is there any other code in you program? Have you inserted debug output? You could test if the run() method is executed.
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