Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Intercept Hardware KeyPress (PTT Button) when app is in background

I'm developing an Android app that intercepts the pressing hardware buttons and makes REST calls to their pressure. The button that I have to intercept is the Push to talk (PTT) button, so not a regular button, such as power button or volume button.

When the application runs in the foreground I use the method onKeyDown (int keyCode, KeyEvent event). The PTT button, as the identifier, has the number 27 and then inside the method I wrote the following lines of code:

if (keyCode == 27) {// I pressed the PTT button}

All this works perfectly.

But now I send the application in the background (with the function moveTaskToBack(true);) and when I press the PTT button I would intercept it.

I am aware of BroadcastReceiver, of IntentFilter and Service, however, these allow you to intercept the limited intent actions (such intent.action.SCREEN_OFF or others normal actions), among which are not able to find the pressure of the PTT button.

Is there any way to intercept the PTT button when the application is in the background?

Thank you

like image 428
Alberto Deidda Avatar asked Mar 12 '23 07:03

Alberto Deidda


1 Answers

The solution to your question depends highly on the device you are using. If you have a phone with a dedicated PTT button, the manufacturer of the phone almost certainly has made an Intent available for app developers such as yourself to intercept PTT down and up events, but you'll need to contact the manufacturer for more information.

For instance, phones from Kyocera, Sonim, and Casio have such Intents available, and you'd simply need to put a receiver declaration in your AndroidManifest.xml, like this for a Kyocera phone:

    <receiver android:exported="true" android:name="com.myapp.receiver.KeyReceiverKyocera">
        <intent-filter android:priority="9999999">
            <action android:name="com.kodiak.intent.action.PTT_BUTTON" />
            <action android:name="com.kyocera.android.intent.action.PTT_BUTTON" />
        </intent-filter>
    </receiver>

Then, a simple BroadcastReceiver class that receives the up and down intents:

public class KeyReceiverKyocera extends BroadcastReceiver
{
    private static boolean keyDown = false;

    @Override
    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();

        if (keyDown)
            processPTTDown();
        else
            processPTTUp();

        keyDown = !keyDown;
    }
}

Hope this helps,

Shawn

like image 76
Shawn Bertrand Avatar answered Apr 27 '23 02:04

Shawn Bertrand