Use an AsyncTask, here is some sample code:
...
private class CounterTask extends AsyncTask<null, null, null> {
@Override
protected void onPreExecute() {
}
@Override
protected Long doInBackground(Uri... uri) {
try {
mCount++;
updateUIHandler.obtainMessage().sendToTarget();
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Long result) {
}
}
public Handler updateUIHandler = new Handler() {
public void handleMessage(Message msg) {
mText.setText(mCount);
}
};
mText
is your TextView and mCount
is your counter, these can be global variables. As iTech has stated you can't update UI from a thread, however you can make a call to a Handler on the UI thread to do the update.
And run the task like this:
new CounterTask().execute(null, null, null);