MEDIA_BUTTON button event ACTION_DOWN and ACTION_UP received at the same time
Asked Answered
E

1

2

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?

Enginery answered 26/9, 2013 at 13:27 Comment(0)
B
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

Blouin answered 18/11, 2013 at 13:3 Comment(1)
You can find a solution for measuring the time described here: https://mcmap.net/q/500546/-how-to-listen-to-quot-action_down-quot-key-pressed-event-in-android-onmediabuttonevent-in-order-to-measure-the-time Working from API level 21 (Build.VERSION_CODES.LOLLIPOP)Tiphani

© 2022 - 2024 — McMap. All rights reserved.