As I understand your question, you want to:
- Detect long presses in the background (some other apps are still
running, and the screen is ON?)
- Detect long presses while the SCREEN is OFF
for booth case, a MEDIA PLAYER is ACTIVE
As it is writen in Android documentation
In previous version of Android, detecting touch events while the screen is off is not possible in Android due to security reasons.
But there are some exceptions, like music players apps, not all media players.
But actually, Touch event is easily detected in some phone like Pixel 5.
it is possible to detect touch events while the screen is off using a Service and a WakeLock. So you have to check the docs, for what version of android you are working on.
If you are using recent android, You may try this code:
public class VolumeButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
int streamType = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_TYPE", -1);
if (streamType == AudioManager.STREAM_MUSIC) {
int oldVolume = intent.getIntExtra("android.media.EXTRA_PREV_VOLUME_STREAM_VALUE", -1);
int newVolume = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_VALUE", -1);
if (newVolume < oldVolume) {
// Volume button was long-pressed
}
}
}
}
}
This code creates a BroadcastReceiver that listens for the android.media.VOLUME_CHANGED_ACTION intent. When this intent is received, it checks whether the volume stream type is STREAM_MUSIC, which corresponds to the media volume.