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
Simply, just create a new service class. Here, using this class you are able to see the Hardware button click event in log. Here i am using volume key as a onKeyEvent.
Make a button click event from your activity to start the service. It will starts your service in background.
Don't forgot to add this service to your manifest.
When you click on btnSave, it will starts your service. Now just move to home screen and click the volume key, you will surely get the result as it works fine for me.
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 ) :
Ref : https://developer.android.com/guide/topics/media-apps/mediabuttons.html
Right from developer.android.com
So, as long as you create a service, and the user exits your app it will still run. Just like the example above.
This should give you all the information you need: Visit this link