How to Programmatically close the notification tray

3.1k views Asked by At

I want to share the GCM notification item. The share button is responding to click events and item gets shared too. Only problem here is, Intent chooser dialog is present below the notification tray. User has to manually close the status bar and then select the app for sharing. I want to close the status bar programmatically, so that when the user clicks share, it directly shows him the dialog to choose the apps.

I found that status bar service can be used to open/close the service. But it's restricted for system apps.

private void closeNotificationTray() {
        Object service = mContext.getSystemService(Context.STATUS_BAR_SERVICE);
        Method collapse;
        try {
            Class<?> statusBarMngr = Class.forName("android.app.StatusBarManager");
            if (Build.VERSION.SDK_INT >= 17)
                collapse = statusBarMngr.getMethod("collapsePanels");
            else
                collapse = statusBarMngr.getMethod("collapse");
            collapse.invoke(service);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

I used the above code. But I'm getting "STATUS_BAR_SERVICE cannot be resoloved" error. And when i added the below permision in the manifest:

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

I'm getting, allowed only for system apps.It's not allowing me to use in my app. Is there any way to use status barservice or any other alternative?

Update:

I solved the above issue with just 2 lines of code. There is no need to call STATUS_BAR_SERVICE.

Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    mContext.sendBroadcast(it);

Calling this intent will automatically closes the notification

1

There are 1 answers

1
Satya Ch On

Yes, this permission "android.permission.STATUS_BAR" is available to only system apps, not to third party apps.

You can try below method:

  1. Create Some notification by passing pending intent into it.
  2. Create pending intent with share as action. Now you will be able to use share option.

@Amanda Fernandez can you try above method