Bhaskar
Bhaskar

Reputation: 169

The error: android.os.NetworkOnMainThreadException

I add Version detection in the entrance of activity. And add the following code in onCreate method.

new Thread(){
         public void run(){
         try{
         checkToUpdate();
         }
            catch(Exception e) {
            }
         }
            }.run();

Now it has a new thread. But why it has the error: android.os.NetworkOnMainThreadException in android 4.0?

thanks in advance!

Upvotes: 0

Views: 918

Answers (4)

MByD
MByD

Reputation: 137362

You should call the start() method.

The run() method is called on the current thread, while the start() method creates a new thread and calls the run() method on the newly created thread.

In earlier Android versions, if you ran a long operation on the main (UI) thread, you didn't get the exception immediately, only after Dalvik detected that the application is not responsive for a few seconds. Now, an exception is thrown if you try to perform network communication on the main thread, to let you find those issues easily at development time.

Upvotes: 1

kumar
kumar

Reputation: 691

Long running tasks and network operations shoudn't be put on onCreate() method because there will a small time allocated to complete the onCreate() method (probably 4 sec or less), You move it to onResume() method, and if possible put it in AsyncTask.

Upvotes: 0

Abhishek Chauhan
Abhishek Chauhan

Reputation: 2014

it should be start() instead of run()

new Thread(){
         public void run()
         {
            try{
            checkToUpdate();
         }
            catch(Exception e) {
            }
         }
            }.start();

And may be you have not added internet permission in manifest file

<manifest xlmns:android...>
 ...
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

Upvotes: 2

Anuj
Anuj

Reputation: 2073

You need to Use AsyncTask or Handler with Thread you can't anymore use the Main thread to do Network Processes after HONEY COMB

Upvotes: 0

Related Questions