Detect home button press in android

后端 未结 17 2172
抹茶落季
抹茶落季 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:10

    Try to create a counter for each screen. If the user touch HOME, then the counter will be zero.

    public void onStart() {
      super.onStart();
      counter++;
    }
    
    public void onStop() {
      super.onStop();
      counter--;    
      if (counter == 0) {
          // Do..
      }
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 09:14

    I needed to start/stop background music in my application when first activity opens and closes or when any activity is paused by home button and then resumed from task manager. Pure playback stopping/resuming in Activity.onPause() and Activity.onResume() interrupted the music for a while, so I had to write the following code:

    @Override
    public void onResume() {
      super.onResume();
    
      // start playback here (if not playing already)
    }
    
    @Override
    public void onPause() {
      super.onPause();
    
      ActivityManager manager = (ActivityManager) this.getSystemService(Activity.ACTIVITY_SERVICE);
      List<ActivityManager.RunningTaskInfo> tasks = manager.getRunningTasks(Integer.MAX_VALUE);
      boolean is_finishing = this.isFinishing();
      boolean is_last = false;
      boolean is_topmost = false;
      for (ActivityManager.RunningTaskInfo task : tasks) {
        if (task.topActivity.getPackageName().startsWith("cz.matelier.skolasmyku")) {
          is_last = task.numRunning == 1;
          is_topmost = task.topActivity.equals(this.getComponentName());
          break;
        }
      }
    
      if ((is_finishing && is_last) || (!is_finishing && is_topmost && !mIsStarting)) {
        mIsStarting = false;
        // stop playback here
      }
    }
    

    which interrupts the playback only when application (all its activities) is closed or when home button is pressed. Unfortunatelly I didn't manage to change order of calls of onPause() method of the starting activity and onResume() of the started actvity when Activity.startActivity() is called (or detect in onPause() that activity is launching another activity other way) so this case have to be handled specially:

    private boolean mIsStarting;
    
    @Override
    public void startActivity(Intent intent) {
      mIsStarting = true;
      super.startActivity(intent);
    }
    

    Another drawback is that this requires GET_TASKS permission added to AndroidManifest.xml:

    <uses-permission
      android:name="android.permission.GET_TASKS"/>
    

    Modifying this code that it only reacts on home button press is straighforward.

    0 讨论(0)
  • 2020-11-22 09:14

    Since you only wish for the root activity to be reshown when the app is launched, maybe you can get this behavior by changing launch modes, etc. in the manifest?

    For instance, have you tried applying the android:clearTaskOnLaunch="true" attribute to your launch activity, perhaps in tandem with android:launchMode="singleInstance"?

    Tasks and Back Stack is a great resource for fine-tuning this sort of behavior.

    0 讨论(0)
  • 2020-11-22 09:16

    Android Home Key handled by the framework layer you can't able to handle this in the application layer level. Because the home button action is already defined in the below level. But If you are developing your custom ROM, then It might be possible. Google restricted the HOME BUTTON override functions because of security reasons.

    0 讨论(0)
  • 2020-11-22 09:19

    Since API 14 you can use the function onTrimMemory() and check for the flag TRIM_MEMORY_UI_HIDDEN. This will tell you that your Application is going to the background.

    So in your custom Application class you can write something like:

    override fun onTrimMemory(level: Int) {
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            // Application going to background, do something
        }
    }
    

    For an in-depth study of this, I invite you to read this article: http://www.developerphil.com/no-you-can-not-override-the-home-button-but-you-dont-have-to/

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