I wish to update the text on the screen every 5 second, I have created a timer to do so. However after the first update it never updates the box again. I am assuming I need to r
I would use a Handler.
private static final int WHAT = 1;
private static final int TIME_TO_WAIT = 5000;
Handler regularHandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
return true;
}
});
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
As an example, that would "Do stuff" every 5000 milliseconds. You can make the Handler react to different events by passing in WHAT as a different integer and handling that in the handleMessage function.
Edit: I would normally place the constants and the Handler in the class as members and the regularHandler.sendEmptyMessageDelayed(...) in onResume() {}
I would also put this in onPause() {}
regularHandler.removeMessages(WHAT)
Edit2: Example:
public class HomeActivity extends Activity implements OnClickListener {
private static final int WHAT = 1;
private static final int TIME_TO_WAIT = 5000;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTitle = (TextView) findViewById(R.id.textTitle);
textArtist = (TextView) findViewById(R.id.textArtist);
}
@Override
public void onResume() {
super.onResume();
regularHandler.sendEmptyMessageDelayed(WHAT, TIME_TO_WAIT);
}
@Override
public void onPause() {
super.onPause();
regularHandler.removeMessages(WHAT);
}
Handler regularHandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
// Do stuff
regularHandler.sendEmptyMessageDelayed(msg.what, TIME_TO_WAIT);
return true;
}
});
}
You need to do it in onResume() and onPause() because if you don't put it in onPause the Handler will continue to loop while your Activity isn't in the foreground. You will want the loop to enable again when it comes back to the foreground (hence onResume()).
Using a handler is a good strategy but you don't really need a custom callback. Instead you can just use postDelayed
with a Runnable
. See this Android doc for details on implementation.
runOnUiThread(new Runnable() {
public void run() {
textTitle.setText(title);
}
});
You cannot update UI from background thread. Whenever you want to make modifications to UI it is suggested to use UI thread