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()).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…