Android Question How to play/pause media in another app?

Inman

Well-Known Member
Licensed User
Longtime User
I am trying to have a background service using which I can play or pause media playback on another app. I believe the basic idea is to send KeyCodes.KEYCODE_MEDIA_PLAY_PAUSE key to the other app. I tried to use SendInput library but the problem is it sends keys to the system, which means it will get executed in the app that was the last one to play media. I couldn't find a way to link key input to a specific package name.

This java code seems to do it. Since it uses intents, there must be a way to set the component name to a specific app. Could you please translate to B4A?
Java:
private static void sendMediaButton(Context context, int keyCode) 
{
    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode);
    Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intent, null);

    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode);
    intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    intent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
    context.sendOrderedBroadcast(intent, null);
}

sendMediaButton(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_PAUSE);
 

DonManfred

Expert
Licensed User
Longtime User
You can not control other apps or send input to other apps other than using Intents.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Try this:
B4X:
Sub Activity_Create(FirstTime As Boolean)
    SendMediaButton(127) 'KEYCODE_MEDIA_PAUSE, 126 = KEYCODE_MEDIA_PLAY
End Sub

Sub SendMediaButton (Keycode As Int)
    Dim keyEvent As JavaObject
    keyEvent.InitializeNewInstance("android.view.KeyEvent", Array(0, Keycode)) 'ACTION_DOWN
    Dim in As Intent
    in.Initialize("android.intent.action.MEDIA_BUTTON", "")
    in.PutExtra("android.intent.extra.KEY_EVENT", keyEvent)
    Dim p As Phone
    p.SendBroadcastIntent(in)
   
    keyEvent.InitializeNewInstance("android.view.KeyEvent", Array(1, Keycode)) 'ACTION_UP
    in.Initialize("android.intent.action.MEDIA_BUTTON", "")
    in.PutExtra("android.intent.extra.KEY_EVENT", keyEvent)
    p.SendBroadcastIntent(in)
End Sub
 
Upvote 0

Inman

Well-Known Member
Licensed User
Longtime User
Thanks Erel. The code worked perfectly for Pause command on all media players I tested. Unfortunately I couldn't use it to start playback on other players. I tried adding packagename of the app I want to control, to the above intents. Still nothing was happening.

I guess the purpose of the above code is not really that. I will keep looking. Thanks anyway.
 
Upvote 0
Top