2

在我的应用程序中,我想测量媒体按钮按下的时间。我注册了一个监听媒体按钮按下的广播接收器:(请原谅愚蠢的错误,因为我是初学者......)

<receiver android:name="MyRec">
   <intent-filter>
      <action android:name="android.intent.action.MEDIA_BUTTON">
         <action android:name="android.intent.action.MEDIA_BUTTON"/>
      </action>
   </intent-filter>
</receiver>

broadcastReceiver 激活活动中的方法(不理想,但这仅用于测试目的):

public void onReceive(Context context, Intent intent) {
   KeyEvent Xevent = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);    
   MainActivity inst = MainActivity.instance();
   if ((Xevent.getAction() == KeyEvent.ACTION_DOWN)){
      inst.startTimer();
      }
   else if ((Xevent.getAction() == KeyEvent.ACTION_UP)) {
      inst.stopTimer();
   }
}

该活动在调用 startTimer() 时占用系统时间,然后在调用 stopTimer 时再次占用系统时间并显示差异:

public void startTimer(){
    pressTime = System.currentTimeMillis();
}

public void stopTimer(){
    pressDuration = System.currentTimeMillis() - pressTime;
    TextView timerTextView = (TextView)findViewById(R.id.timerText);
    timerTextView.setText(Long.toString(pressDuration));
}

问题是,从我看到的两个事件同时调用,当我放开按钮时,最终使计时器计数的时间非常短(几毫秒),与我按下的持续时间无关按钮。

我究竟做错了什么?

4

1 回答 1

1

您不需要使用自己的计时器。接收动作时可以使用参数的getDownTimegetEventTime方法。eventKeyEvent.ACTION_UP

<action android:name="android.intent.action.MEDIA_BUTTON"/>此外,不需要嵌套在清单中

于 2013-11-18T13:03:34.277 回答