Updating UI with Runnable & postDelayed not working with timer app
Replace
mHandler.postAtTime(this, 1000);
with
mHandler.postDelayed(this, 1000);
- You need to do UI updates in the UI thread.
You need to create a Handler in the UI thread to run tasks in the UI thread.
public class MainActivity extends AppCompatActivity private Handler mHandler; @Override protected void onCreate(Bundle savedInstanceState) { mHandler = new Handler(); // This to create the Handler in the UI thread // ... }
This might be more along the lines of what you are looking for:
private Runnable mUpdateTimeTask = new Runnable() { public void run() { final long start = mStartTime; long elapseTime = System.currentTimeMillis() - start; int seconds = (int) (elapseTime / 1000); int minutes = seconds / 60; seconds = seconds % 60; if (seconds < 10) { mTimeTextField.setText("" + minutes + ":0" + seconds); } else { mTimeTextField.setText("" + minutes + ":" + seconds); } // add a delay to adjust for computation time long delay = (1000 - (elapseTime%1000)); mHandler.postDelayed(this, delay); } };
I found this to be a good way to add a time to video's