Detect home button press in android

后端 未结 17 2554
抹茶落季
抹茶落季 2020-11-22 08:22

This has been driving me nuts for a while now.

Is there any way of reliably detecting if the home button has been pressed in an android application?

Failing

17条回答
  •  佛祖请我去吃肉
    2020-11-22 09:11

    I had this problem, and since overriding the onKeyDown() method didn't accomplish anything because of the underlying android system didn't call this method, I solved this with overriding onBackPressed(), and I had a boolean value set there to false, because I pressed back, let me show you what I mean in code:

    import android.util.Log;
    public class HomeButtonActivity extends Activity {
        boolean homePressed = false;
        // override onCreate() here.
    
        @Override
        public void onBackPressed() {
            homePressed = false; // simply set homePressed to false
        }
    
        @Overide
        public void onResume() {
            super.onResume();
            homePressed = true; // default: other wise onBackPressed will set it to false
        }
    
        @Override
        public void onPause() {
            super.onPause();
            if(homePressed) { Log.i("homePressed", "yay"); }
        }
    

    So the reason why this worked is because the only way to navigate outside this activity is by pressing back or home so if back was pressed then i know the cause wasn't home, but otherwise the cause was home, therefore i set the default boolean value for homePressed to be true. However this will only work with a single activity instance in your application because otherwise you have more possibilities to cause the onPause() method to be called.

提交回复
热议问题