Android: How can I detect selfie-stick button click when my app is in background

Viewed 312

I am building an Android app, which detects the selfie-stick button click connected to the mobile audio jack.

I am able to capture the button click if the app is in the foreground, but not in the background.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
   switch (keyCode) {
       case KeyEvent.KEYCODE_VOLUME_UP:
           Toast.makeText(CustomPadActivity.this, "BUTTON clicked", Toast.LENGTH_SHORT).show();
           return true;
   }
   return super.onKeyDown(keyCode, event);
}

I tried using the broadcast receiver with action android.intent.action.MEDIA_BUTTON but it is not capturing the button click at all.

Manifest:

<receiver android:name=".MyReceiver" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

And my Receiver class:

public class MyReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "BUTTON clicked", Toast.LENGTH_SHORT).show();
    }

}

I read somewhere I need to play a piece of music if I want to capture the button click. The app is not an audio player. I don't want to play audio in the app.

I am just trying to capture the selfie-stick button click when my app is in the background.

1 Answers

This is of course

onKeyEvent only can be callbacks in the activity

Services simply do not receive KeyEvent callbacks.

Add intent to AndroidManifest in Activtiy

<intent-filter>
    <action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>

and add this in your Activity or it will not show on your lockscreen.

@Override
public void onAttachedToWindow() {
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
}
Related