【发布时间】:2013-10-02 12:08:40
【问题描述】:
在我的应用中,我想测量媒体按钮按下的时间。我注册了一个可以监听媒体按钮按下的广播接收器:(请原谅愚蠢的错误,因为我是初学者......)
<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 激活 Activity 中的方法(不理想,但这只是为了测试目的):
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() 被调用时,Activity 会占用系统时间,然后在 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));
}
问题是,从我看到的两个事件被同时调用,当我放开按钮时,最终使计时器计数的时间非常短(几毫秒),与我按下按钮的持续时间。
我做错了什么?
【问题讨论】:
标签: android broadcastreceiver headset headphones