Search code examples
javaandroidkotlinandroid-developer-api

Is it possible to pause any video (mediaplayer) APP in Android when pull down the notification panel?


Assume I have the AOSP source code, How can I pause the APP in the foreground when pulling down the notification panel? I've googled and find an APP can listen the event onWindowFocusChange and take some action proactively, but how can I pause ANY APP when pulling down the notification panel, without modify every APP respectively (which is impractical)?

Is there a way that I can call the onPause function of any foreground App from the SystemUI process?


Solution

  • You can use below method for detecting the notification panel pull,

    In your manifest file

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

    In your activity override the onWindowFocusChanged() and write the below code.

    This uses the permission

    @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();
            }
        }
    }
    

    Then in your app request for audio focus, refer below link

    https://developer.android.com/guide/topics/media-apps/audio-focus#java

    This will pause audio access for all other apps.