写了个程序,点击发送按钮的时候给主handler发送消息,主handler接收到消息后处理,处理后给子线程handler发送消息,子线程handler接收到消息后处理完再给主handler发送消息。如此循环。在点击停止按钮的事件中写了handler.removeMessages(1);来移除handler,不过多次点击无效。log日志一直循环打印。求大神指点停止handler消息的方法。public class FourActivity extends Activity implements OnClickListener{ private Button btn_send; private Button btn_stop; private Handler threadHandler; //创建主线程的handler private Handler handler = new Handler(){ public void handleMessage(android.os.Message msg) { Message message = new Message(); System.out.println("main handler"); //向子线程发送消息 threadHandler.sendMessageDelayed(message, 1000); }; }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.four_activity); btn_send = (Button)findViewById(R.id.button1); btn_stop = (Button)findViewById(R.id.button2); btn_send.setOnClickListener(this); btn_stop.setOnClickListener(this); HandlerThread ht = new HandlerThread("handlerThread"); ht.start(); //创建子线程的handler threadHandler = new Handler(ht.getLooper()){ public void handleMessage(Message msg) { Message message = new Message(); System.out.println("thread handler"); //向主线程发送消息 handler.sendMessageDelayed(message, 1000); }; }; } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.button1: handler.sendEmptyMessage(1); break; case R.id.button2: handler.removeMessages(1); break; default: break; } } }
1 回答
addsion_y
TA贡献9条经验 获得超1个赞
既然你handler.removeMessages(1);
那么也应该sendEmptyMessageDelayed(1, 1000)
可以试试看行不行.
Remove any pending posts of messages with code 'what' that are in the message queue.
- 1 回答
- 0 关注
- 2473 浏览
添加回答
举报
0/150
提交
取消