MEDIA_BUTTON button event ACTION_DOWN and ACTION_UP received at the same time

▼魔方 西西 提交于 2019-12-11 13:23:32

问题


In my app I want to measure how long the media button press was. I registered a broadcastReceiver that listens to the media button press: (please excuse stupid mistakes as I am a beginner...)

<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>

The broadcastReceiver activates a method in an activity (not ideal, but this is just for testing purposes):

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();
   }
}

The activity takes system time when startTimer() is called and then again when stopTimer is called and shows the diff:

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));
}

The issue is that from what I see both events are called at the same time, both when I let go of the button, what eventually makes the timer count a very short time period (few millisecond) that are not related to the duration I press the button.

What am I doing wrong?


回答1:


You don't need to use your own timers. You can use the getDownTime and getEventTime methods of the event parameter when receiving the KeyEvent.ACTION_UP action.

Also, The nested <action android:name="android.intent.action.MEDIA_BUTTON"/> in your manifest is not required



来源:https://stackoverflow.com/questions/19029669/media-button-button-event-action-down-and-action-up-received-at-the-same-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!