Can I keep Android activity alive in background, until user doesn't kill or close the application.
I want to detect user clicks in background some specific hardware button clicks, as onKeyDown
is not available in service, I need to keep my activity alive in background until user kills the app.
Does android allows such behavior ?
Update :
I was able to solve this using following approach :
1] Use foreground service, Ref : https://developer.android.com/guide/components/services.html#Foreground
2] To handle media button click use below approach after Android 21 + ( Use this code in onCreate() of your foreground service ) :
mediaSession = new MediaSessionCompat(this, TAG);
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
if (mediaButtonEvent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) {
KeyEvent event = (KeyEvent) mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode() && event.getAction() == KeyEvent.ACTION_DOWN) {
Log.e(TAG, "Media Button clicked");
handleHeadphoneClick();
}
}
return false;
}
});
mediaSession.setActive(true);
Ref : https://developer.android.com/guide/topics/media-apps/mediabuttons.html