Press home button to stop service

后端 未结 3 383
谎友^
谎友^ 2021-01-16 12:08

i want to if the user press home button my service will be stop , this is my code but it\'s not working for me, please help me:

@Override
public boolean onKe         


        
相关标签:
3条回答
  • 2021-01-16 12:46

    If you're trying to make sure the service only runs when the related activity is visible, a better solution would be to stop the service in the onPause() method of whatever activity the user is running. That way, the event is handled when the user presses "back" and when the user presses "home".

    Likewise, you can bind your service to the activity (or activities). The bound service will be destroyed when all activities bound to it stop.

    0 讨论(0)
  • 2021-01-16 12:46

    public static final int KEYCODE_HOME

    This key is handled by the framework and is never delivered to applications.

    Source

    0 讨论(0)
  • 2021-01-16 12:47

    Make a root activity and add this,

    @Override
        public void onTrimMemory(int level) {
            super.onTrimMemory(level);
            if (level == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
                // Get called every-time when application went to background.
                System.exit(0);
            }
    
        }
    

    extend each activity with rootActivity, it will shutdown service on home/menu button press

    0 讨论(0)
提交回复
热议问题