【问题标题】:MEDIA_BUTTON button event ACTION_DOWN and ACTION_UP received at the same time同时收到 MEDIA_BUTTON 按钮事件 ACTION_DOWN 和 ACTION_UP
【发布时间】: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


    【解决方案1】:

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

    另外,清单中的嵌套&lt;action android:name="android.intent.action.MEDIA_BUTTON"/&gt; 不是必需的

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多