Handler.postDelayed()
executes the Runnable
in the Thread
in which the Handler
was created. In your case you create it in your Activity on the UI Thread. So the first time, the Runnable
gets executed in a separate Thread, but the second time in the UI Thread.
I get `android.os.NetworkOnMainThreadException` while using a seperate thread
-
29-06-2022 - |
Question
In my Activity I use a handler
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
//do GUI stuff, edit views, etc..
}
};
I also have a Runnable
, which posts to php and waits for a json response
Runnable runnable3 = new Runnable() {
public void run() {
JSONParserArray jsonParserRun = new JSONParserArray();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("p1", "myParam1"));
try {
String link = "http://mylink.com/someFileOnServer.php";
JSONArray jArray = jsonParserRun.makeHttpRequest(link , "POST",
params);
if (jArray != null && jArray.length() != 0) {
} else {
//either null (because of throwing exception) or empty
}
} catch (Exception e) {
}
}
handler.sendEmptyMessage(0);
handler.postDelayed(runnable, 30000);
}
I repeat the task every 30 seconds, finally inside my onCreate() I creat a thread and passing it the Runnable
@Override
public void onCreate(Bundle savedInstanceState) {
//other stuff
Thread t = new Thread(runnable3);
t.start();
}
This code throws android.os.NetworkOnMainThreadException
even thought I am starting a new thread and passing the Runnable
to it. The class JSONParserArray works fine in other cases (so no worries there)
However, when I run this method inside the Runnable
, it is working fine.
private boolean hasActiveInternetConnection() {
try {
new Socket().connect(new InetSocketAddress("google.com", 80), 3000);
return true;
} catch (Exception e) {
Log.i("tag", e.toString());
return false;
}
}
Solution
OTHER TIPS
There is another way to overcome the exception.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
In your manifest
<uses-permission android:name="android.permission.INTERNET"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow