Keep activity alive in background until user doesn't kill or close app?

前端 未结 3 702
终归单人心
终归单人心 2021-01-15 10:03

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

3条回答
  •  一生所求
    2021-01-15 10:54

    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

提交回复
热议问题