开发日志 170215

第二天写开发日志,嗯……

今天还是在做那个智能小船的控制器。昨天做完了消息队列,今天处理了长按按钮连续触发事件的问题。目前长按已经可以连续触发事件了,具体消息处理还没有写。

连续触发主要是用OnTouchListener来监听MotionEvent.ACTION_DOWN和MotionEvent.ACTION_UP事件。当监听到按钮按下时启动一个新线程,持续作出响应,然后当监听到抬起事件后把这个线程结束掉。

线程的创建和结束可以使用Thread类来处理,不过使用ScheduledExecutorService也是个不错的方案。

这是我的主要参考链接:http://blog.csdn.net/u010983881/article/details/49927411

出于备忘目的,贴上本段的核心代码:

目前只是按下按钮后简单的每100ms发UDP包,具体的操作内容尚待添加。

设定监听器:

    /* Create the OnTouchListener of motion control button, such as WASD.
     Call callback_motionUpdate to handle all event.
    */
    View.OnTouchListener ctlBtnListener = new View.OnTouchListener() {
      @Override
      public boolean onTouch(View v, MotionEvent event) {
        return callback_motionUpdate(v, event);
      }
    };

    //Set OnTouchListener of motion control button, such as WASD.
    findViewById(R.id.btnDown).setOnTouchListener(ctlBtnListener);
    findViewById(R.id.btnUP).setOnTouchListener(ctlBtnListener);
    findViewById(R.id.btnLeft).setOnTouchListener(ctlBtnListener);
    findViewById(R.id.btnRight).setOnTouchListener(ctlBtnListener);
  /**
   * A pointer class point to ScheduledExecutorService class
   */
  private class pScheduledExecutorService {
    ScheduledExecutorService SES;
  }

  // 4 ScheduledExecutorService pointer
  private pScheduledExecutorService
      up = new pScheduledExecutorService(),
      down = new pScheduledExecutorService(),
      left = new pScheduledExecutorService(),
      right = new pScheduledExecutorService();

  //The Callback Function of WASD.
    private boolean callback_motionUpdate(View view, MotionEvent event) {
    pScheduledExecutorService thisSES;
    switch (view.getId()) {
      case R.id.btnUP:
        thisSES = up;
        break;
      case R.id.btnDown:
        thisSES = down;
        break;
      case R.id.btnLeft:
        thisSES = left;
        break;
      case R.id.btnRight:
        thisSES = right;
        break;
      default:
        return false;
    }
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        thisSES.SES = Executors.newSingleThreadScheduledExecutor();
        thisSES.SES.scheduleWithFixedDelay(new Runnable() {
          @Override
          public void run() {
            //TODO Change the Var of Status.
            ctlMsgSender.mHandler.sendEmptyMessage(msgType.ctlUpdate);
          }
        }, 0, 100, TimeUnit.MILLISECONDS);    //每间隔100ms发送Message
        break;
      case MotionEvent.ACTION_UP:
        if (thisSES.SES != null) {
          thisSES.SES.shutdownNow();
          thisSES.SES = null;
        }
        break;
      default:
        return false;
    }
        ctlMsgSender.mHandler.sendEmptyMessage(msgType.ctlUpdate);
    return false;
    }

 

发表评论