单击主页键和应用程序在后台运行

时间:2013-10-03 09:42:45

标签: android

如果按下主页按钮,我试图输入代码然后在background.how中运行应用程序进程在我的应用程序中使用编码在后台运行我的应用程序的代码。但是当点击时它不起作用主页

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK ||
            keyCode == KeyEvent.KEYCODE_HOME && event.getRepeatCount() == 0) {
        this.moveTaskToBack(true);               
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

1 个答案:

答案 0 :(得分:1)

点击此处,按下主页按钮或您的应用程序将要离开。

public void onPause(){
    super.onPause();
        Context context = getApplicationContext();
                ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
                List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                if (!taskInfo.isEmpty()) {
                  ComponentName topActivity = taskInfo.get(0).topActivity; 
                  if (!topActivity.getPackageName().equals(context.getPackageName())) {

                    Toast.makeText(xYourClassNamex.this, "YOU LEFT YOUR APP. ", Toast.LENGTH_SHORT).show();
                  }
                }
      }