Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is the code that I wrote. It works like a charm. May be you can optimize it for better logic. But you will get the point with it. The key is to use flags. <strong>Short press is a press where we press volume button for short time and release</strong>. So <strong>onKeyUp</strong> is the one which will help us detect short presses. </p> <pre><code>package com.example.demo; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; public class TestVolumeActivity extends Activity { boolean flag = false; boolean flag2 = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_splash_screen, menu); return true; } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { Log.d("Test", "Long press!"); flag = false; flag2 = true; return true; } return super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { event.startTracking(); if (flag2 == true) { flag = false; } else { flag = true; flag2 = false; } return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { event.startTracking(); if (flag) { Log.d("Test", "Short"); } flag = true; flag2 = false; return true; } return super.onKeyUp(keyCode, event); } } </code></pre> <p><strong>Logcat for all long presses(No short press detected):</strong></p> <pre><code>10-18 02:06:15.369: D/Test(16834): Long press! 10-18 02:06:18.683: D/Test(16834): Long press! 10-18 02:06:21.566: D/Test(16834): Long press! 10-18 02:06:23.738: D/Test(16834): Long press! </code></pre> <p><strong>Logcat for all short presses:</strong></p> <pre><code>10-18 02:07:42.422: D/Test(16834): Short 10-18 02:07:43.203: D/Test(16834): Short 10-18 02:07:43.663: D/Test(16834): Short 10-18 02:07:44.144: D/Test(16834): Short </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload