首页 > 代码库 > 迅雷android面试题
迅雷android面试题
一、android几种定时器的机制及区别。
答:在android中,经常用到的定时器主要有以下几种实现:
1、采用handler与线程的sleep(long)方法
开启一个线程,,每隔1s向Handler发送消息
public class MainActivity extends Activity { private Handler myhandler; private static int timemessage=0x01; private int timer=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myhandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if(msg.what==timemessage){ System.out.println("timer="+(++timer)); } } }; new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub while(true){ try { System.out.println("执行了"); Thread.sleep(2000); myhandler.sendEmptyMessage(timemessage); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }).start(); } }
2、采用Handler自带的postDelayed(Runnable,long)方法
利用延迟几秒发送Message,嵌套postDelayed()实现定时器。
public class MainActivity extends Activity { private Handler myhandler; private static int timemessage = 0x01; private int timer = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myhandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if (msg.what == timemessage) { System.out.println("timer=" + (++timer)); } } }; myhandler.postDelayed(new Runnable() { @Override public void run() { // TODO Auto-generated method stub myhandler.sendEmptyMessage(timemessage); myhandler.postDelayed(this, 1000); if (timer == 10) { myhandler.removeMessages(timemessage); } } }, 1000); } }3、采用Handler与Timer、TimerTask结合的方法
利用Timer类的schedule()方法,每隔一段时间做什么事情实现定时器。
public class MainActivity extends Activity { private Handler myhandler; private static int timemessage = 0x01; private int timer = 0; private Timer timerobject; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myhandler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub if (msg.what == timemessage) { System.out.println("timer=" + (++timer)); } } }; timerobject=new Timer(); timerobject.schedule(new TimerTask() { //1s后,在每隔1s做什么事情 @Override public void run() { // TODO Auto-generated method stub myhandler.sendEmptyMessage(timemessage); } }, 1000,1000); } }
二、利用Listview显示姓名和年龄,采用SimpleAdapter实现。
public class MainActivity extends Activity { private ListView mylistview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mylistview = (ListView) findViewById(R.id.listviewid); List<Map<String, Object>> listdata = http://www.mamicode.com/new ArrayList
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。