Reputation: 145
I need to catch longpress event of media button even when the device is locked or the app is in background. onKey listener does not work for apps in background. I have a working example with BroadcastReceiver, but it only works for short press. I am using AudioManager to register the receiver. What i can see in console when i press the button for a long time is this:
I/MediaSessionService(684): voice-based interactions: about to use ACTION_WEB_SEARCH
I/ActivityManager(684): START u0 {act=android.speech.action.WEB_SEARCH flg=0x10800000} from uid 1000 on display 0
So i have tried listening to ACTION_WEB_SEARCH by context.registerReceiver() method with no success. I also added receiver with intent-filter into manifest file.
Is there any other way i could try? Or does anyone know about a working solution? I have been searching and testing this one functionality for 5 days now and i am getting really angry. =D
Upvotes: 1
Views: 726
Reputation: 131
I found the answer for the exact same issue you describe here.
All you need to do is add intent-filter to an activity you want to start by long pressing the media button.
WEB_SEARCH is called when the screen is unlocked.
VOICE_SEARCH_HANDS_FREE is called when the screen is locked.
Manifest file with added actions to the MainActivity:
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:screenOrientation="portrait">
<intent-filter android:priority="1000000">
<action android:name="android.speech.action.VOICE_SEARCH_HANDS_FREE" />
<action android:name="android.speech.action.WEB_SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
The first time you launch your app and long press the button a small dialog box on the bottom of the screen will appear. The dialog box asks if you want to complete the action with the Google app or your own app, they both listen to the same actions.
Don't forget to 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);
}
Upvotes: 2