How To Handle Home Button In Android

时光毁灭记忆、已成空白 提交于 2019-11-29 08:37:49

You Does not get Home Button click event .But When u press Home Button call this method

  @Override
        protected void onStop() {

            super.onStop();
        }

You can't tell if a HOME button was clicked and you can't stop your app from being hidden when the HOME button is pressed, but you can tell if your app is no longer visible (either BACK key, HOME key, or another app got the foreground).

Just override onPause or onStop, and add a log there.

I found the answer pls add code given below-

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





@Override
public void onStop() {
    if (isApplicationSentToBackground(this)){
        //put your code here what u want to do

    }
    super.onStop();
}

make change to manifests file-

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

You Can not detect home press event any more. But you can get home press event by other way Logically It works for me hope useful to you also.

Define this in activity

public static boolean OnPause = false;
public static boolean OnResume = false;

put this method in activity

 @Override 
  protected void onPause() 
  { 
      // TODO Auto-generated method stub
      super.onPause(); 

       OnPause  = true;

  }

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();

    OnResume = true;        

}
@Override
protected void onStop() {
    // TODO Auto-generated method stub
    super.onStop();

    if(OnPause == true && OnResume == false)
    {
        Log.e("My activity ", " **** home is press *** ");
        //Do Your Home press code Here.

    }

    OnPause = false;
    OnResume = false;

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!