简体   繁体   English

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

[英]Call method when home button pressed

I have this method in one of my Android Activities:我的 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);
}

But, even though the KEYCODE_HOME is valid, the log method never fires.但是,即使 KEYCODE_HOME 有效,日志方法也不会触发。 This works for the back button though.这适用于后退按钮。 Does anyone know why this is and how to get this to work?有谁知道这是为什么以及如何使它工作?

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. Home 按钮是一个非常危险的按钮,因此需要覆盖,因此,Android 不会让您以与执行 BACK 按钮相同的方式覆盖其行为。

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.)如果不替换设备的默认主屏幕,我会担心 HOME 按钮过载,但这是可能的(根据上面线程中的讨论。)

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:在您的活动的 onPause() 中,您必须包含以下 if 条件:

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

The function isFinishing() returns a boolean.函数 isFinishing() 返回一个布尔值。 True if your App is actually closing, False if your app is still running but for example the screen turns off.如果您的应用程序实际上正在关闭,则为 True,如果您的应用程序仍在运行,但例如屏幕关闭,则为 False。

Hope it helps!希望能帮助到你!

The HOME button cannot be intercepted by applications. HOME键不能被应用拦截。 This is a by-design behavior in Android.这是 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. Home 按钮被认为是用户的“安全区”,将始终启动用户配置的家庭应用程序。

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:这意味着它在其 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>

When pressing the home button, the current home app's activity's onNewIntent will be called.当按下 home 键时,当前 home 应用的 Activity 的onNewIntent将被调用。

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:我发现当我按下按钮 HOME 时 onStop() 方法被调用。您可以使用以下代码段来监视它:

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

KeyEvent.KEYCODE_HOME can NOT be intercepted. KeyEvent.KEYCODE_HOME不能被拦截。

It would be quite bad if it would be possible.如果有可能,那将是非常糟糕的。

(Edit) : I just see Nicks answer, which is perfectly complete ;) (编辑) :我只看到尼克斯的回答,这是完全完整的;)

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

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..总之,在活动中放置一个布尔值,当活动切换发生时(startactivity 事件),设置变量并在 onpause 事件中检查此变量。

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

I also struggled with HOME button for awhile.我也挣扎了一段时间的 HOME 按钮。 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使用布尔值将应用程序的状态保持在 SharedPreferences 上

on each activity在每项活动中

onResume() -> set appactive=true onResume() -> 设置 appactive=true

onPause() -> set appactive=false onPause() -> 设置 appactive=false

and the background service checks the appstate in each loop, skips the action并且后台服务在每个循环中检查 appstate,跳过操作

IF appactive=false如果 appactive=false

it works well for me, at least not draining the battery anymore, hope this helps....它对我来说效果很好,至少不再耗尽电池电量,希望这会有所帮助....

define the variables in your activity like this:在您的activity定义变量,如下所示:

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:onCreate方法或onResume方法上注册接收器,如下所示:

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>

https://www.tutorialspoint.com/detect-home-button-press-in-android 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(); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM