按下主页按钮时的调用方法

发布于 2024-10-14 07:49:44 字数 444 浏览 5 评论 0原文

我的 Android 活动之一中有此方法:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        Log.d("Test", "Back button pressed!");
    }
    else if(keyCode == KeyEvent.KEYCODE_HOME)
    {
        Log.d("Test", "Home button pressed!");
    }
    return super.onKeyDown(keyCode, event);
}

但是,即使 KEYCODE_HOME 有效,日志方法也永远不会触发。但这适用于后退按钮。有谁知道这是为什么以及如何让它发挥作用?

I have this method in one of my Android Activities:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        Log.d("Test", "Back button pressed!");
    }
    else if(keyCode == KeyEvent.KEYCODE_HOME)
    {
        Log.d("Test", "Home button pressed!");
    }
    return super.onKeyDown(keyCode, event);
}

But, even though the KEYCODE_HOME is valid, the log method never fires. This works for the back button though. Does anyone know why this is and how to get this to work?

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

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

发布评论

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

评论(11

三生路 2024-10-21 07:49:44

Home 按钮是一个非常危险的覆盖按钮,因此,Android 不会让您像覆盖 BACK 按钮一样覆盖其行为。

看看这个讨论。< /a>

您会注意到主页按钮似乎是作为意图调用来实现的,因此您最终必须向您的活动添加一个意图类别。然后,每当用户点击主页时,您的应用程序都会显示为一个选项。您应该考虑您希望通过主页按钮实现什么目的。如果它不是要替换设备的默认主屏幕,我会担心 HOME 按钮超载,但这是可能的(根据上面线程中的讨论)。

The Home button is a very dangerous button to override and, because of that, Android will not let you override its behavior the same way you do the BACK button.

Take a look at this discussion.

You will notice that the home button seems to be implemented as a intent invocation, so you'll end up having to add an intent category to your activity. Then, any time the user hits home, your app will show up as an option. You should consider what it is you are looking to accomplish with the home button. If its not to replace the default home screen of the device, I would be wary of overloading the HOME button, but it is possible (per discussion in above thread.)

鹤仙姿 2024-10-21 07:49:44

我花了将近一个月的时间才解决这个问题。刚才我解决了这个问题。
在您的活动的 onPause() 中,您必须包含以下 if 条件:

    if (this.isFinishing()){
        //Insert your finishing code here
    }

函数 isFinishing() 返回一个布尔值。如果您的应用程序实际上正在关闭,则为 True;如果您的应用程序仍在运行,但例如屏幕关闭,则为 False。

希望有帮助!

It took me almost a month to get through this. Just now I solved this issue.
In your activity's onPause() you have to include the following if condition:

    if (this.isFinishing()){
        //Insert your finishing code here
    }

The function isFinishing() returns a boolean. True if your App is actually closing, False if your app is still running but for example the screen turns off.

Hope it helps!

时常饿 2024-10-21 07:49:44

HOME按钮不能被应用程序拦截。这是 Android 中的设计行为。原因是为了防止恶意应用程序获得对您手机的控制(如果用户无法按返回或主页,他可能永远无法退出该应用程序)。
“主页”按钮被视为用户的“安全区”,并且始终会启动用户配置的主页应用程序。

上述唯一的例外是配置为家庭替代的任何应用程序。这意味着它在相关 Activity 的 AndroidManifest.xml 中声明了以下内容:

<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.HOME" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

按下主页按钮时,将调用当前主页应用的 Activity 的 onNewIntent

The HOME button cannot be intercepted by applications. This is a by-design behavior in Android. The reason is to prevent malicious apps from gaining control over your phone (If the user cannot press back or home, he might never be able to exit the app).
The Home button is considered the user's "safe zone" and will always launch the user's configured home app.

The only exception to the above is any app configured as home replacement. Which means it has the following declared in its AndroidManifest.xml for the relevant activity:

<intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.HOME" />
   <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

When pressing the home button, the current home app's activity's onNewIntent will be called.

惟欲睡 2024-10-21 07:49:44

我发现当我按下HOME按钮时,onStop()方法被调用。您可以使用下面的代码来监控它:

@Override
    protected void onStop() 
    {
        super.onStop();
        Log.d(tag, "MYonStop is called");
        // insert here your instructions
    }

I found that when I press the button HOME the onStop() method is called.You can use the following piece of code to monitor it:

@Override
    protected void onStop() 
    {
        super.onStop();
        Log.d(tag, "MYonStop is called");
        // insert here your instructions
    }
笑,眼淚并存 2024-10-21 07:49:44

我有一个处理主页按钮按下的简单解决方案。这是我的代码,它可能很有用:

public class LifeCycleActivity extends Activity {


boolean activitySwitchFlag = false;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        activitySwitchFlag = true;
        // activity switch stuff..
        return true;
    }
    return false;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override 
public void onPause(){
    super.onPause();
    Log.v("TAG", "onPause" );
    if(activitySwitchFlag)
        Log.v("TAG", "activity switch");
    else
        Log.v("TAG", "home button");
    activitySwitchFlag = false;
}

public void gotoNext(View view){
    activitySwitchFlag = true;
    startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}

}

作为摘要,在活动中放置一个布尔值,当发生活动切换(startactivity 事件)时,设置变量并在 onpause 事件中检查此变量。

I have a simple solution on handling home button press. Here is my code, it can be useful:

public class LifeCycleActivity extends Activity {


boolean activitySwitchFlag = false;

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) 
{
    if(keyCode == KeyEvent.KEYCODE_BACK)
    {
        activitySwitchFlag = true;
        // activity switch stuff..
        return true;
    }
    return false;
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}

@Override 
public void onPause(){
    super.onPause();
    Log.v("TAG", "onPause" );
    if(activitySwitchFlag)
        Log.v("TAG", "activity switch");
    else
        Log.v("TAG", "home button");
    activitySwitchFlag = false;
}

public void gotoNext(View view){
    activitySwitchFlag = true;
    startActivity(new Intent(LifeCycleActivity.this, NextActivity.class));
}

}

As a summary, put a boolean in the activity, when activity switch occurs(startactivity event), set the variable and in onpause event check this variable..

楠木可依 2024-10-21 07:49:44

KeyEvent.KEYCODE_HOME 无法被拦截。

如果可以的话那就太糟糕了。

(编辑):我刚刚看到尼克斯的回答,非常完整;)

KeyEvent.KEYCODE_HOME can NOT be intercepted.

It would be quite bad if it would be possible.

(Edit): I just see Nicks answer, which is perfectly complete ;)

桃酥萝莉 2024-10-21 07:49:44

使用广播接收器

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // something
    // for home listen
    InnerRecevier innerReceiver = new InnerRecevier();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    registerReceiver(innerReceiver, intentFilter);

}



// for home listen
class InnerRecevier extends BroadcastReceiver {

    final String SYSTEM_DIALOG_REASON_KEY = "reason";
    final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            if (reason != null) {
                if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    // home is Pressed
                }
            }
        }
    }
}

Using BroadcastReceiver

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // something
    // for home listen
    InnerRecevier innerReceiver = new InnerRecevier();
    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    registerReceiver(innerReceiver, intentFilter);

}



// for home listen
class InnerRecevier extends BroadcastReceiver {

    final String SYSTEM_DIALOG_REASON_KEY = "reason";
    final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
            String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
            if (reason != null) {
                if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                    // home is Pressed
                }
            }
        }
    }
}
明媚如初 2024-10-21 07:49:44

使用 onPause() 方法在主页按钮上执行您想要执行的操作。

use onPause() method to do what you want to do on home button.

权谋诡计 2024-10-21 07:49:44

我也曾因 HOME 键的使用而苦恼了一段时间。
当用户单击“主页”按钮时,我想停止/跳过后台服务(轮询位置)。

这是我实现的“类似黑客”的解决方案;

使用布尔值在 SharedPreferences 上保留应用程序的状态

使用每个活动的

onResume() ->设置appactive=true

onPause() ->设置appactive=false

,后台服务在每个循环中检查appstate,跳过该操作

IF appactive=false

它对我来说效果很好,至少不再耗尽电池,
希望这有帮助......

I also struggled with HOME button for awhile.
I wanted to stop/skip a background service (which polls location) when user clicks HOME button.

here is what I implemented as "hack-like" solution;

keep the state of the app on SharedPreferences using boolean value

on each activity

onResume() -> set appactive=true

onPause() -> set appactive=false

and the background service checks the appstate in each loop, skips the action

IF appactive=false

it works well for me, at least not draining the battery anymore,
hope this helps....

懵少女 2024-10-21 07:49:44

像这样定义 activity 中的变量:像

const val SYSTEM_DIALOG_REASON_KEY = "reason"
const val SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"
const val SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"

这样定义广播接收器类:

class ServiceActionsReceiver: BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            
            val action = intent!!.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY)
                if (reason != null) {
                    if (reason == SYSTEM_DIALOG_REASON_HOME_KEY) {
                        //do what you want to do when home pressed
                    } else if (reason == SYSTEM_DIALOG_REASON_RECENT_APPS) {
                        //do what you want to do when recent apps pressed
                    }
                }
            }
        }
    }

onCreate 方法或 onResume 方法上注册接收器,如下所示:

val filter = IntentFilter()
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
registerReceiver(receiver, filter)

add清单中的接收者如下所示:

<receiver android:name=".ServiceActionsReceiver">
            <intent-filter >
                <actionandroid:name="android.intent.action.CLOSE_SYSTEM_DIALOGS"/>
            </intent-filter>
</receiver>

define the variables in your activity like this:

const val SYSTEM_DIALOG_REASON_KEY = "reason"
const val SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps"
const val SYSTEM_DIALOG_REASON_HOME_KEY = "homekey"

define your broadcast receiver class like this:

class ServiceActionsReceiver: BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            
            val action = intent!!.action
            if (action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS) {
                val reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY)
                if (reason != null) {
                    if (reason == SYSTEM_DIALOG_REASON_HOME_KEY) {
                        //do what you want to do when home pressed
                    } else if (reason == SYSTEM_DIALOG_REASON_RECENT_APPS) {
                        //do what you want to do when recent apps pressed
                    }
                }
            }
        }
    }

register reciver on onCreate method or onResume method like this:

val filter = IntentFilter()
filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
registerReceiver(receiver, filter)

add receiver in your manifest like this:

<receiver android:name=".ServiceActionsReceiver">
            <intent-filter >
                <actionandroid:name="android.intent.action.CLOSE_SYSTEM_DIALOGS"/>
            </intent-filter>
</receiver>
岁月静好 2024-10-21 07:49:44

https://www.tutorialspoint.com/detect-home -android 中的按钮按下

  @Override
   protected void onUserLeaveHint() {
      text.setText("Home buton pressed");
      Toast.makeText(MainActivity.this,"Home buton pressed",Toast.LENGTH_LONG).show();
      super.onUserLeaveHint();
   }

https://www.tutorialspoint.com/detect-home-button-press-in-android

  @Override
   protected void onUserLeaveHint() {
      text.setText("Home buton pressed");
      Toast.makeText(MainActivity.this,"Home buton pressed",Toast.LENGTH_LONG).show();
      super.onUserLeaveHint();
   }

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