问题描述
在我的应用中,我想测量媒体按钮按下的时间.我注册了一个BroadcastReceiver,它可以监听媒体按钮的按下情况:(请原谅愚蠢的错误,因为我是初学者...)
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>
broadcastReceiver在活动中激活方法(不是理想的方法,但这只是出于测试目的):
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();
}
}
当调用startTimer()时,该活动占用系统时间,而当调用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.
我在做什么错了?
推荐答案
您不需要使用自己的计时器.收到KeyEvent.ACTION_UP
操作时,可以使用event
参数的getDownTime
和getEventTime
方法.
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.
此外,清单中不需要嵌套的<action android:name="android.intent.action.MEDIA_BUTTON"/>
Also, The nested <action android:name="android.intent.action.MEDIA_BUTTON"/>
in your manifest is not required
这篇关于同时收到MEDIA_BUTTON按钮事件ACTION_DOWN和ACTION_UP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!