Detect home button press in android

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

    
    

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

提交回复
热议问题