Is it possible to assume that the code in run
will be executed in a new thread, or should I use AsyncTask
?
Timer myTimer = new Timer(); // final Handler uiHandler = new Handler(); myTimer.schedule(new TimerTask() { // @Override public void run() { uiHandler.post(new Runnable() { @Override public void run() { } }); } ; }, 0L, 10L * 1000); // - 10000 , 0 .
UPDATED
I got an error in this code:
Timer myTimer = new Timer(); final Handler uiHandler = new Handler(); myTimer.schedule(new TimerTask() { @Override public void run() { while (songRefreshing) { uiHandler.post(new Runnable() { @Override public void run() { try { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = null; response = httpclient.execute(new HttpGet(Const.php_url)); StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { ByteArrayOutputStream out = new ByteArrayOutputStream(); response.getEntity().writeTo(out); out.close(); String responseString = out.toString(); if (app.getCurSong() == null || app.getCurSong().intern() != responseString.intern()) { app.setCurSong(responseString); song_name.setText(app.getCurSong()); Log.d(LOG_TAG, "refreshCurSung - " + responseString); } } else { response.getEntity().getContent().close(); throw new IOException(statusLine.getReasonPhrase()); } } catch (IOException e) { e.printStackTrace(); Log.d(LOG_TAG, e.toString()); } } }); } } ; }, 0L, 10L * 1000);
Error:
android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1178) at java.net.InetAddress.lookupHostByName(InetAddress.java:394) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:245) at java.net.InetAddress.getAllByName(InetAddress.java:220) at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137) at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:590) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:510) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:488)
Does this mean that TimerTask is not executing in a new thread?
source share