android - 同时接收到 MEDIA_BUTTON 按钮事件 ACTION_DOWN 和 ACTION_UP

标签 android broadcastreceiver headset headphones

在我的应用程序中,我想测量按下媒体按钮的时间。我注册了一个监听媒体按钮按下的 broadcastReceiver:(请原谅愚蠢的错误,因为我是初学者...)

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

Activity 在调用 startTimer() 时占用系统时间,然后在调用 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));
}

问题是,据我所知,这两个事件同时被调用,当我松开按钮时,最终使计时器计数的时间非常短(几毫秒),与我按下按钮的持续时间。

我做错了什么?

最佳答案

您不需要使用自己的计时器。您可以使用 getDownTimegetEventTime event 的方法接收 KeyEvent.ACTION_UP 时的参数行动。

还有,嵌套的<action android:name="android.intent.action.MEDIA_BUTTON"/>在你的 list 中不是必需的

关于android - 同时接收到 MEDIA_BUTTON 按钮事件 ACTION_DOWN 和 ACTION_UP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19029669/

相关文章:

php - 除了发送参数之外,是否有传递给浏览器的信息可以告诉网站是什么应用程序访问了它?

android - 使用位图时android中的图像尺寸不正确

Android 设备选择器显示我的设备,但我的应用程序无法在我的手机上启动! :(

Android BroadcastReceiver 收不到任何广播事件

android - 模拟器控制被真正的安卓设备禁用

Android Messenger 应用程序使用服务

android - 权限拒绝 : not allowed to send broadcast android. intent.action.HEADSET_PLUG

android - 如何将Android设备用作另一部手机的蓝牙耳机?

android:即使应用程序关闭也能收到短信