检测android中的home按钮按下

发布于 2024-12-27 09:54:57 字数 1128 浏览 1 评论 0原文

这已经让我发疯有一段时间了。

有没有什么方法可以可靠地检测 Android 应用程序中是否按下了主页按钮?

如果做不到这一点,是否有一种可靠的方法来判断是什么导致活动进入 onPause?即我们能否检测到它是否是由新活动启动或按返回/主页引起的。

我看到的一个建议是重写 onPause() 并调用 isFinishing() ,但是当按下主页按钮时,这将返回 false,就像新活动开始时一样,因此无法区分两者。

非常感谢任何帮助。

** 更新** : 感谢@android-hungry提供此链接: https://nishandroid.blogspot.com/

覆盖以下方法:

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
}

那么按下主页按钮将触发以下事件:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {     

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
       //The Code Want to Perform. 
    }
});

我不确定这行代码是否有任何副作用:

this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);   

因此,与普遍的看法相反,您实际上可以监听主页键。令人担忧的是,您可能会返回 false 并且让 home 键不执行任何操作。

更新: 正如预期的那样,这会产生一些副作用 - 启用此模式后,嵌入视频和谷歌地图似乎不可见。

更新: 据说这个 hack 从 Android 4.0 开始不再有效

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 that, is there a robust way of telling what caused an activity to go into onPause? i.e Can we detect if it was caused by a new activity launching or by pressing back/home.

One suggestion I have seen is to override onPause() and call isFinishing() but this will return false when pressing the home button just as it would if a new activity is starting so this fails to distinguish between the two.

Any help much appreciated.

** Update** :
Thanks to @android-hungry for this link: https://nishandroid.blogspot.com/

Overiding the following method:

@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);           
}

Then the following event WILL get fired for home button presses:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {     

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
       //The Code Want to Perform. 
    }
});

I'm not sure if there are any side effects with this line:

this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);   

So it would seem that contrary to popular belief, you can in fact listen out for the home key. Worryingly, you can return false and have the home key do nothing.

Update:
As expected, there are some side affects with this - it seems that embedded videos and google maps are not visible with this mode enabled.

Update:
Supposedly this hack no longer works as of Android 4.0 onwards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

怀念你的温柔 2025-01-03 09:54:57

以下代码对我有用:)

HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    @Override
    public void onHomePressed() {
        // do something here...
    }
    @Override
    public void onHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

public class HomeWatcher {

    static final String TAG = "hg";
    private Context mContext;
    private IntentFilter mFilter;
    private OnHomePressedListener mListener;
    private InnerReceiver mReceiver;

    public HomeWatcher(Context context) {
        mContext = context;
        mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    public void setOnHomePressedListener(OnHomePressedListener listener) {
        mListener = listener;
        mReceiver = new InnerReceiver();
    }

    public void startWatch() {
        if (mReceiver != null) {
            mContext.registerReceiver(mReceiver, mFilter);
        }
    }

    public void stopWatch() {
        if (mReceiver != null) {
            mContext.unregisterReceiver(mReceiver);
        }
    }

    class InnerReceiver extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    Log.e(TAG, "action:" + action + ",reason:" + reason);
                    if (mListener != null) {
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                            mListener.onHomePressed();
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                            mListener.onHomeLongPressed();
                        }
                    }
                }
            }
        }
    }
}
public interface OnHomePressedListener {
    void onHomePressed();
    void onHomeLongPressed();
}

Following code works for me :)

HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    @Override
    public void onHomePressed() {
        // do something here...
    }
    @Override
    public void onHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

public class HomeWatcher {

    static final String TAG = "hg";
    private Context mContext;
    private IntentFilter mFilter;
    private OnHomePressedListener mListener;
    private InnerReceiver mReceiver;

    public HomeWatcher(Context context) {
        mContext = context;
        mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    public void setOnHomePressedListener(OnHomePressedListener listener) {
        mListener = listener;
        mReceiver = new InnerReceiver();
    }

    public void startWatch() {
        if (mReceiver != null) {
            mContext.registerReceiver(mReceiver, mFilter);
        }
    }

    public void stopWatch() {
        if (mReceiver != null) {
            mContext.unregisterReceiver(mReceiver);
        }
    }

    class InnerReceiver extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    Log.e(TAG, "action:" + action + ",reason:" + reason);
                    if (mListener != null) {
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                            mListener.onHomePressed();
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                            mListener.onHomeLongPressed();
                        }
                    }
                }
            }
        }
    }
}
public interface OnHomePressedListener {
    void onHomePressed();
    void onHomeLongPressed();
}
春花秋月 2025-01-03 09:54:57

这是一个老问题,但它可能会对某人有所帮助。

@Override
protected void onUserLeaveHint()
{
    Log.d("onUserLeaveHint","Home button pressed");
    super.onUserLeaveHint();
}

根据文档,当用户单击主页按钮或当某些事情中断您的应用程序(例如来电)时,将调用 onUserLeaveHint() 方法。

这对我有用..:)

This is an old question but it might help someone.

@Override
protected void onUserLeaveHint()
{
    Log.d("onUserLeaveHint","Home button pressed");
    super.onUserLeaveHint();
}

According to the documentation, the onUserLeaveHint() method is called when the user clicks the home button OR when something interrupts your application (like an incoming phone call).

This works for me.. :)

廻憶裏菂餘溫 2025-01-03 09:54:57

不可能从 Android 应用程序中检测和/或拦截 HOME 按钮。这是系统内置的,以防止无法退出的恶意应用程序。

It is impossible to detect and/or intercept the HOME button from within an Android app. This is built into the system to prevent malicious apps that cannot be exited.

执手闯天涯 2025-01-03 09:54:57

当第一个活动打开和关闭时,或者当任何活动被主页按钮暂停然后从任务管理器恢复时,我需要在应用程序中启动/停止背景音乐。 Activity.onPause()Activity.onResume() 中的纯播放停止/恢复会中断音乐一段时间,因此我必须编写以下代码

@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
  }
}

:仅当应用程序(其所有活动)关闭或按下主页按钮时才播放。不幸的是,当 Activity.startActivity( ) 被调用(或者在 onPause() 中检测该 Activity 正在以其他方式启动另一个 Activity),因此必须特殊处理这种情况:

private boolean mIsStarting;

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

另一个缺点是这需要添加到 AndroidManifest.xml 中的 GET_TASKS 权限:

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

修改此代码使其仅对按下主页按钮做出反应非常简单。

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.

牛↙奶布丁 2025-01-03 09:54:57

onUserLeaveHint();

覆盖此活动类方法。这将检测主页键单击。
该方法在 Activity 的 onPause() 回调之前调用。但是,当 Activity 被中断(例如正在调用的 Activity 进入前台)时,该方法不会被调用,除了当用户单击 Home 键时它将调用的中断之外。

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();
    Log.d(TAG, "home key clicked");
}

onUserLeaveHint();

override this activity class method.This will detect the home key click .
This method is called right before the activity's onPause() callback.But it will not be called when an activity is interrupted like a in-call activity comes into foreground, apart from that interruptions it will call when user click home key.

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();
    Log.d(TAG, "home key clicked");
}
牛↙奶布丁 2025-01-03 09:54:57

覆盖活动中的 onUserLeaveHint()。当新的 Activity 过来或用户按下后退键时,该 Activity 永远不会有任何回调。

Override onUserLeaveHint() in the activity. There will never be any callback to the activity when a new activity comes over it or user presses back press.

权谋诡计 2025-01-03 09:54:57

从 API 14 开始,您可以使用函数 onTrimMemory() 并检查标志 TRIM_MEMORY_UI_HIDDEN。这将告诉您您的应用程序将进入后台。

因此,在您的自定义应用程序类中,您可以编写如下内容:

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

为了深入研究这一点,我邀请您阅读这篇文章:
http ://www.developerphil.com/no-you-can-not-override-the-home-button-but-you-dont-have-to/

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/

飘过的浮云 2025-01-03 09:54:57

尝试为每个屏幕创建一个计数器。如果用户触摸“HOME”,则计数器将为零。

public void onStart() {
  super.onStart();
  counter++;
}

public void onStop() {
  super.onStop();
  counter--;    
  if (counter == 0) {
      // Do..
  }
}

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..
  }
}
月下客 2025-01-03 09:54:57

您可以考虑 Andreas Shrade 在他的帖子中提出的解决方案 如何在 Android 中创建工作 Kiosk 模式。这有点hacky,但考虑到阻止拦截主页按钮的原因,它必须是;)

You might consider a solution by Andreas Shrade in his post on How-To Create a Working Kiosk Mode in Android. It's a bit hacky, but given the reasons that interception of the home button is prevented it has to be ;)

幽蝶幻影 2025-01-03 09:54:57

由于您只希望在应用程序启动时重新显示根活动,也许您可​​以通过更改清单中的启动模式等来获得此行为?

例如,您是否尝试过应用 android:clearTaskOnLaunch="true" 属性到您的启动活动,可能与 android:launchMode="singleInstance"

任务和返回堆栈是一个很好的资源微调这种行为。

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.

咽泪装欢 2025-01-03 09:54:57

我遇到了这个问题,并且由于重写 onKeyDown() 方法没有完成任何事情,因为底层 Android 系统没有调用此方法,所以我通过重写 onBackPressed() 解决了这个问题,并且我在那里设置了一个布尔值 false ,因为我按了后退,让我向您展示我在代码中的意思:

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"); }
    }

所以这有效的原因是因为在该活动之外导航的唯一方法是按后退或主页,所以如果按后退,那么我知道原因是'不在家,但除此之外原因是 home,因此我将 homePressed 的默认布尔值设置为 true。然而,这仅适用于应用程序中的单个活动实例,否则您有更多的可能性导致调用 onPause() 方法。

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.

勿忘心安 2025-01-03 09:54:57

最近我试图检测主页按钮,因为我需要它执行与方法“onBackPressed()”相同的操作。为了做到这一点,我必须像这样重写方法“onSupportNavigateUp()”:

override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

它工作得很好。 =)

Recently I was trying to detect the home press button, because I needed it to do the same as the method "onBackPressed()". In order to do this, I had to override the method "onSupportNavigateUp()" like this:

override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

It worked perfectly. =)

枫以 2025-01-03 09:54:57

输入图片此处描述
Android Home 键由框架层处理,您无法在应用程序层处理此问题。因为主页按钮操作已经在下面的级别中定义了。但如果您正在开发自定义 ROM,那么这可能是可能的。出于安全原因,Google 限制了 HOME BUTTON 覆盖功能。

enter image description here
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.

如若梦似彩虹 2025-01-03 09:54:57

您的应用程序的一个选项是使用 android.intent.category.HOME Intent 编写替换主屏幕。我相信这种类型的 Intent 你可以看到主页按钮。

更多详细信息:

http://developer.android.com/guide/主题/intents/intents-filters.html#imatch

An option for your application would be to write a replacement Home Screen using the android.intent.category.HOME Intent. I believe this type of Intent you can see the home button.

More details:

http://developer.android.com/guide/topics/intents/intents-filters.html#imatch

信愁 2025-01-03 09:54:57

改变 home 键的行为不是一个好主意。这就是为什么 Google 不允许您覆盖 home 键。一般来说,我不会乱动主页键。如果您的应用程序因任何原因陷入困境,您需要为用户提供一种退出应用程序的方法。

我认为任何解决办法都会产生不必要的副作用。

It's a bad idea to change the behavior of the home key. This is why Google doesn't allow you to override the home key. I wouldn't mess with the home key generally speaking. You need to give the user a way to get out of your app if it goes off into the weeds for whatever reason.

I'd image any work around will have unwanted side effects.

別甾虛僞 2025-01-03 09:54:57

Jack 的答案非常适合 click 事件,而 longClick 则考虑作为 menu 按钮单击。

顺便说一句,如果有人想知道如何通过 kotlin 进行操作,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)
    }

    fun stopWatch() {
        context.unregisterReceiver(mReceiver)
    }

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {
                    listener.onHomeButtonClick()
                }
            }
        }
    } 
}

Jack's answer is perfectly working for click event while longClick is considering is as menu button click.

By the way, if anyone is wondering how to do via kotlin,

class HomeButtonReceiver(private var context: Context,private var listener: OnHomeButtonClickListener) {
    private val mFilter: IntentFilter = IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
    private var mReceiver: InnerReceiver = InnerReceiver()

    fun startWatch() {
        context.registerReceiver(mReceiver, mFilter)
    }

    fun stopWatch() {
        context.unregisterReceiver(mReceiver)
    }

    inner class InnerReceiver: BroadcastReceiver() {
        private val systemDialogReasonKey = "reason"
        private val systemDialogReasonHomeKey = "homekey"
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent?.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(systemDialogReasonKey)
                if (reason != null && reason == systemDialogReasonHomeKey) {
                    listener.onHomeButtonClick()
                }
            }
        }
    } 
}
苏别ゝ 2025-01-03 09:54:57

已解决:这适用于 BACK、HOME 和 TASK OVERVIEW

@Override
public void onBackPressed() {
}

@Override
public void onPause() {
    if (isApplicationSentToBackground(MainActivity.this)){
        // Do what you want to do on detecting Home Key being Pressed
        Toast.makeText(this, "You pressed the task button!", Toast.LENGTH_LONG).show();
    }
    super.onPause();
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);

    activityManager.moveTaskToFront(getTaskId(), 0);
}

@SuppressWarnings("deprecation")
public boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}

并添加到清单:android.permission.REORDER_TASKS

SOLVED: This works for BACK, HOME and TASK OVERVIEW

@Override
public void onBackPressed() {
}

@Override
public void onPause() {
    if (isApplicationSentToBackground(MainActivity.this)){
        // Do what you want to do on detecting Home Key being Pressed
        Toast.makeText(this, "You pressed the task button!", Toast.LENGTH_LONG).show();
    }
    super.onPause();
    ActivityManager activityManager = (ActivityManager) getApplicationContext()
            .getSystemService(Context.ACTIVITY_SERVICE);

    activityManager.moveTaskToFront(getTaskId(), 0);
}

@SuppressWarnings("deprecation")
public boolean isApplicationSentToBackground(final Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}

And add to manifest: android.permission.REORDER_TASKS

む无字情书 2025-01-03 09:54:57

这对我有用。
您可以重写 onUserLeaveHint 方法
https://www.tutorialspoint.com/detect-home-button-按入android

@Override
    protected void onUserLeaveHint() {
        //
        super.onUserLeaveHint();
    }

This works for me.
You can override onUserLeaveHint method
https://www.tutorialspoint.com/detect-home-button-press-in-android

@Override
    protected void onUserLeaveHint() {
        //
        super.onUserLeaveHint();
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文