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