Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle the notification bar in android

I know I can expand the notification bar by reflection

    Class<?> statusbarManager = Class.forName( "android.app.StatusBarManager" );
    Method showsb;
    if (Build.VERSION.SDK_INT >= 17) {
        showsb = statusbarManager.getMethod("expandNotificationsPanel");
    }
    else {
        showsb = statusbarManager.getMethod("expand");
    }
    showsb.invoke( getSystemService( "statusbar" ) );

However, is there a way to expand it if it is collapsed, and collapse it if it is already expanded?

There is a toggle function for StatusBarManager in the android docs but it doesn't work for me.

EDITED

I am calling this function from inside a bound service.

like image 561
daniely Avatar asked Oct 19 '22 23:10

daniely


1 Answers

I think that you may be missing the needed permissions. Make sure that you have the EXPAND_STATUS_BAR permission in your Manifest.xml:

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

Looking around, I found this code:

Object sbservice = getSystemService( "statusbar" );
Class<?> statusbarManager = Class.forName( "android.app.StatusBarManager" );
Method showsb = statusbarManager.getMethod( "expand" );
showsb.invoke( sbservice );

You may want to try it.

EDIT:

For actually detecting if it is down or not, see this answer. Here's what it looks like:

Override the onWindowFocusChanged() method in your activity with the code below:

In the permissions:

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

The overriding:

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    try
    {
        if(!hasFocus)
        {
            Object service  = getSystemService("statusbar");
            Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
            Method collapse = statusbarManager.getMethod("collapse");
            collapse .setAccessible(true);
            collapse .invoke(service);
        }
    }
    catch(Exception ex)
    {
        if(!hasFocus)
        {
            try {
                Object service  = getSystemService("statusbar");
                Class<?> statusbarManager = Class.forName("android.app.StatusBarManager");
                Method collapse = statusbarManager.getMethod("collapse");
                collapse .setAccessible(true);
                collapse .invoke(service);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();                
            }
            ex.printStackTrace();
        }
    }
}
like image 97
Alex K Avatar answered Oct 28 '22 14:10

Alex K