Reputation: 4366
Can I consider that code in run
will be executed in new Thread or I must 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); // 10s interval
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 it mean that TimerTask don't executing in new thread?
Upvotes: 5
Views: 6873
Reputation: 6778
To answer your question directly, a quote taken from here:
Class Overview
Timers schedule one-shot or recurring tasks for execution. Prefer ScheduledThreadPoolExecutor for new code.
Each timer has one thread on which tasks are executed sequentially. When this thread is busy running a task, runnable tasks may be subject to delays.
One-shot are scheduled to run at an absolute time or after a relative delay.
Recurring tasks are scheduled with either a fixed period or a fixed rate:
With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period. With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time. When a timer is no longer needed, users should call cancel(), which releases the timer's thread and other resources. Timers not explicitly cancelled may hold resources indefinitely.
This class does not offer guarantees about the real-time nature of task scheduling. Multiple threads can share a single timer without synchronization.
So yeah, it's a Thread.
UPDATE (following the update of the Question):
The current implementation could contain a lot of flaws, that's why I would recommend you to put the code from the Runnable
in an AsyncTask
(and put the whole bunch of code in the doInBackground
method). There you can easily control it.
Furthermore, I think that @Overriding
the run()
two times one inside of another could lead you to a deadlock or something. Since the TimerTask
is in fact a Thread, then I don't think you need a separate Runnable
inside of it.
Remove the implementation of the Runnable
for a start and try to launch the TimerTask
with the HttpClient
inside of it (without the Runnable
). If you can't manage to do it, then put the code (as suggested) in an AsyncTask
(you'll have a prettier implementation like this anyway).
Thx
Upvotes: 6