Android中的线程


Android 平台中多线程应用很广泛,在 UI 更新、游戏开发和耗时处理(网络通信等)等方面都需要多线程。 Android 线程涉及到的技术有: Handler, Message,MessageQueue,Looper,HandlerThread。

public void onCreate(Bundle savedInstanceState) {

           super.onCreate(savedInstanceState);

           setContentView(R.layout.main);

 

           btnEnd = (Button) findViewById(R.id.btnEnd);

           btnEnd.setOnClickListener(new OnClickListener() {

                    @Override

                    public void onClick(View v) {

                             isRunning = false;

                    }

           });

          

           labelTimer = (TextView) findViewById(R.id.labelTimer);

          

           HandlerThread thread = new HandlerThread("MyHandlerThread");

           thread.start();

          

           handler = new Handler(thread.getLooper());

          

           Runnable r = new Runnable() {

                    public void run() {

                             if (isRunning) {

                                       labelTimer.setText(" 逝去了 " +timer + " ");

                                       timer++;

                                       handler.postDelayed(this, 1000);

                             }

 

                    }

           };

           handler.postDelayed(r, 1000);

 

}

}

new HandlerThread("MyHandlerThread") 创建 HandlerThread 线程,通过 thread.start() 方法启动该线程。 HandlerThread getLooper() 方法可以获得与 HandlerThread 线程对象关联的 Looper 对象。再用 Looper 对象构建 new Handler(looper)


发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>