问题
I Am a New Android Developer, I know Handle The Back Button but I Don't Know How To Handle Home Button, when I Clicked Home Button, I Tried Lot Of Methods, But Not Used, Please Any One Help To Me and Solve My Problem. I have used following code,
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_HOME)
{
Toast.makeText(this, "Click Home ", Toast.LENGTH_LONG).show();
}
return super.onKeyDown(keyCode, event);
}
回答1:
You Does not get Home Button click event
.But When u press Home Button
call this method
@Override
protected void onStop() {
super.onStop();
}
回答2:
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.
回答3:
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" />
回答4:
Android Home Key handled by the framework layer you can't able to handle this in the application layer level. Because the home button action is already defined in the below level. But If you are developing your custom ROM, then It might be possible. Google restricted the HOME BUTTON override functions because of security reasons.
回答5:
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;
}
来源:https://stackoverflow.com/questions/10869814/how-to-handle-home-button-in-android