Capturing HOME intent programmatically

2019-02-20 04:12发布

问题:

I need my activity to handle HOME button press with a receiver programmatically, but the event is not firing. I can, however, successfully register and capture this intent filter if I declare it in a manifest.xml activity section. Here's the code for the receiver that's not working:

BroadcastReceiver br;

br = new BroadcastReceiver() {
       @Override
       public void onReceive(Context context, Intent intent) {
               return;  // I put a breakpoint here to see if this gets called
       }
};


IntentFilter intf = new IntentFilter();
intf.addAction(Intent.ACTION_MAIN);
intf.addCategory(Intent.CATEGORY_HOME);
intf.addCategory(Intent.CATEGORY_DEFAULT);

registerReceiver(br, intf);

Does anyone know why this doesn't capture the home button click?

By the way, I tried working around this by creating another activity and specifying its intent filter in the manifest. I set the activity enabled="false" in the manifest but I couldn't figure out how to enable that activity at run time. Bottom line, I only want to register the home button intent filter for my application only when my application is running, and I can't figure out how to do that.

回答1:

If you are trying to implement a replacement home screen, you need your Intent filter to be in the manifest -- see the Home sample app in the SDK.

If you are trying to block the HOME key, please don't.



回答2:

There should never be a case where you should need to override the home-button, it is there to make sure the user always maintain control over his phone. What exactly are you trying to do? If you want to detect when your activity are no longer visible, you should override onStop().