Android Example Capture volume keys events while app is in the background

Could some Java guru kindly convert the following codes into B4A code for me, if possible, please? I would greatly appreciate it!

I'm looking for a reliable solution as a background service to intercept volume key press events with screen off(just anything indicating key_press is enough for my app, either Up or Down key).
I've tried both intent based solution and BroadcastReceiver approach, and neither of them meets my need.

I found the following Java code on StackOverflow website.

Java code for detecting volume key press with screen off:
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.media.VolumeProviderCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;

public class PlayerService extends Service {
    private MediaSessionCompat mediaSession;

    [USER=69643]@override[/USER]
    public void onCreate() {
        super.onCreate();
        mediaSession = new MediaSessionCompat(this, "PlayerService");
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
                MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
                .setState(PlaybackStateCompat.STATE_PLAYING, 0, 0) //you simulate a player which plays something.
                .build());

        //this will only work on Lollipop and up, see https://code.google.com/p/android/issues/detail?id=224134
        VolumeProviderCompat myVolumeProvider =
                new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_RELATIVE, /*max volume*/100, /*initial volume level*/50) {
            [USER=69643]@override[/USER]
            public void onAdjustVolume(int direction) {
                /*
                -1 -- volume down
                1 -- volume up
                0 -- volume button released
                 */
            }
        };

        mediaSession.setPlaybackToRemote(myVolumeProvider);
        mediaSession.setActive(true);
    }


    [USER=69643]@override[/USER]
    public IBinder onBind(Intent intent) {
        return null;
    }

    [USER=69643]@override[/USER]
    public void onDestroy() {
        super.onDestroy();
        mediaSession.release();
    }
}

manifest entry:
<application ...>
    ...
    <service android:name=".PlayerService"/>
</application>

code in Activity:
[USER=69643]@override[/USER]
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    startService(new Intent(this, PlayerService.class));
}


TIA
 

hears

Active Member
Licensed User
Longtime User

press event is work,

but how to Capture key release event ?

 

Gandalf

Member
Licensed User
Longtime User

press event is work,

but how to Capture key release event ?

I never tried it myself yet, but try looking into intent's extra once intent is intercepted. Something like this is described here. If there's ACTION_DOWN, maybe there can be ACTION_UP...
 

Guenter Becker

Active Member
Licensed User
See the attached project.

Note that this is Android 5+ (minSdkVersion=21).
Hi Erel
I used your project and it works as expected. I changed the code to
Modification:
Private Sub Adjust_Volume (Direction As Int)
    Log($"Volume changed: ${Direction}"$)
    B4XPages.ShowPage("MainPage") ' <<<<<<<<<<<<'
End Sub
and changed the Manifest to work with Android 31.

I started the App (Your Project) on my Samsung S21 and after being active I started another App to become the new active one. Pressing the Volume Button the App (Your Project) does intercept the button press and shows the Log Output but the B4XPage is not shown.

My target is to solve this situation:
One App (Your Project) is in the Background and an other App is active on the screen.
Pressing the Volume Button the active App goes to the Background and the backgrounded App becomes active.

Could you give me an example what to code in the Private Sub. Than you in advance.
 

Guenter Becker

Active Member
Licensed User
Hi Erel sorry for the reply,
I just found the solution. I comes with Draw-OverPermissions. I created a class with yout code and put the permission request code in the Crate SUb of the B4XPage and now it works.
Thank you.
 
Top