有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java重写Home按钮的功能

在安卓系统中,我可以很容易地覆盖后退按钮的功能,但对于我的应用程序,我需要覆盖home button。例如,用户在Activity A中,当他按下home按钮时,activity B is launched。我试过做以下的事情,但失败了

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

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
        startActivity(new Intent(this, ActivityB.class));

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

我确信这是可以做到的,因为在Nova Launcher中,当用户在home screen上并且他presses the home button时,启动器为用户提供了一个list of home screens跳转到的位置。我需要同样的功能。如何才能做到这一点

问候


共 (3) 个答案

  1. # 1 楼答案

    试试这个:

    @Override
        protected void onUserLeaveHint() {
            if (!navigating) {
                Intent intent2 = new Intent();
                intent2.setClass(ActivityA.this, ActivityB.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                forceHome(this, intent2);
            }
            super.onUserLeaveHint();
        }
    
    public static void forceHome(Context paramContext, Intent paramIntent) {
    
            if (paramIntent != null) {
                ((AlarmManager) paramContext.getSystemService(ALARM)).set(1,
                        System.currentTimeMillis(),
                        PendingIntent.getActivity(paramContext, 0, paramIntent, 0));
            }
    
        }
    

    作为android的一项安全功能,该活动仅在5秒后启动。如果你想立即启动它。使用你自己的Home Launcher

  2. # 2 楼答案

    尝试重写此方法并编写代码

     @Override
     protected void onStop() 
     {
         super.onStop();
         startActivity(new Intent(this, ActivityB.class));
     }
    
  3. # 3 楼答案

    不,您不能覆盖HomeButton的功能。这是出于安全原因,因此恶意应用程序不会控制您的主页按钮

    如果您想处理主屏幕中的主按钮

    我不确定下面的内容是否有用

    您可以重写onUserLeaveHint

    protected void onUserLeaveHint ()如果你想

    Added in API level 3Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback. This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.