How can I programmatically open/close notifications in Android?

前端 未结 7 2489
无人及你
无人及你 2020-12-04 09:51

I\'ve searched everywhere, but can\'t find anything in the SDK or on Google on how to do this. I know it\'s possible because all the custom launchers are able to do it via a

7条回答
  •  我在风中等你
    2020-12-04 10:50

    Sadly there's still no official API (requested here), but for now, you can use this code, which I've generalized from all of the answers I've found :

    // based on https://gist.github.com/XinyueZ/7bad2c02be425b350b7f 
    // requires permission: "android.permission.EXPAND_STATUS_BAR"
    @SuppressLint("WrongConstant", "PrivateApi")
    fun setExpandNotificationDrawer(context: Context, expand: Boolean) {
        try {
            val statusBarService = context.getSystemService("statusbar")
            val methodName =
                    if (expand)
                        if (Build.VERSION.SDK_INT >= 17) "expandNotificationsPanel" else "expand"
                    else
                        if (Build.VERSION.SDK_INT >= 17) "collapsePanels" else "collapse"
            val statusBarManager: Class<*> = Class.forName("android.app.StatusBarManager")
            val method: Method = statusBarManager.getMethod(methodName)
            method.invoke(statusBarService)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    

提交回复
热议问题