Android的Handler使用
如何每隔一段时间进行一些操作呢,Handler就可以做到。 下面的Demo的功能为每隔3秒显示MyItems数组中的不同数据。
public class MainActivity extends Activity { private int count = 0; private static final String[] MyItems = { "Here is a Item1", "Here is a Item2", "Here is a Item3", "Here is a Item4" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Timer timer = new Timer(); timer.scheduleAtFixedRate(new Newtask(), 10, 3000); } private Handler hand = new Handler(){ public void handleMessage(Message msg){ switch(msg.what) { case 1: Toast.makeText(MainActivity.this, MyItems[count], Toast.LENGTH_SHORT).show(); if(count == 3) count = 0; else count++; break; } }; }; private class Newtask extends TimerTask { @Override public void run() { // TODO Auto-generated method stub Message msg = new Message(); msg.what = 1; hand.sendMessage(msg); } } }
下面的文章讲解的比较详细:
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!