我可以认为运行中的代码将在新线程中执行或者我必须使用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 миллисекунд до первого запуска.
更新
我在这段代码中出错了:
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); // 10s interval
错误:
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)
这是否意味着TimerTask不在新线程中执行?