On Android, how to detect a system dialog is displayed (power options, recent apps, low battery…)?

我怕爱的太早我们不能终老 提交于 2019-12-18 04:14:28

问题


Hi Stackoverflowers (I know, that doesn't sound like it should...)

Well I think It's almost all in the question: I'd like to catch anything that causes the display of my Activity to get even partially hidden, e.g. power options, recent apps tray, low battery notification, etc... and I'm having a hard time to detect these system events.

I was pretty sure onPause() would be called when such events happen, but it seems to be wrong... or is it me?

Any other idea?... I'd preferably not hook on each system broadcast action individually, since I'd like to be as generic as possible (and react to ANYTHING that hides my Activity).

Thanks for any input!


回答1:


On working on a kiosk style app I know that some Dialogs come to the foreground and can be detected by

    ActivityManager activityManager = (ActivityManager)getBaseContext()
       .getSystemService(Activity.ACTIVITY_SERVICE);
    String className = activityManager.getRunningTasks(1).get(0).topActivity.getClassName();

An example for that is the bluetooth-binding dialog that brings the com.android.settings to the foreground.

A counter-example is the power-button dialog (Turn off, Reboot etc) that does not come to the foreground.

Note that you can close system dialogs (even the power-button dialog) with this broadcast:

    Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        sendBroadcast(closeDialog);

But on most (all newer?) devices this Broadcast will even close the software keyboard, so it is not advisable to have a service running that frequently sends it as the user will then be unable to enter anything into a text field.

Note that such behaviour will definetly gratify your app a status as beeing malware, keeping it from beeing published on google play.




回答2:


I was pretty sure onPause() would be called when such events happen, but it seems to be wrong... or is it me?

onPause() will be called if another activity takes over foreground input. So, if a third-party app came to the foreground, even with a dialog-themed activity, onPause() would be called.

There is no requirement for onPause() to be called from OS components, though.

I'd preferably not hook on each system broadcast action individually, since I'd like to be as generic as possible (and react to ANYTHING that hides my Activity).

What you want is not possible. Not all of the things you list have broadcast Intents, and there are other techniques that people can use (e.g., Toasts) that will obscure part of your activity of which you will have no knowledge.



来源:https://stackoverflow.com/questions/8942366/on-android-how-to-detect-a-system-dialog-is-displayed-power-options-recent-ap

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