Android implements global volume key long press monitoring

Implementation method: Calling the hidden interface of the media session service requires the system permission android.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER. To obtain this permission, the manufacturer's signature is generally required.

Since the MediaSessionManager.OnVolumeKeyLongPressListener interface is hidden, we need to create a corresponding interface in our own project. First create the package android.media.session, and then create an interface named MediaSessionManager$OnVolumeKeyLongPressListener. This naming is to avoid conflicts with the system's MediaSessionManager. Class conflict, the interface code is as follows:

public interface MediaSessionManager$OnVolumeKeyLongPressListener {
    void onVolumeKeyLongPress(KeyEvent event);
}

Then reflect and call the setOnVolumeKeyLongPressListener method to monitor the volume key long press event. The code is as follows:

public class MediaKeyUtils {


    /**
     * 设置音量键长按监听
     * @param context
     * @param listener
     */
    public static void setVolumeKeyLongPressListener(Context context, MediaSessionManager$OnVolumeKeyLongPressListener listener) {
        MediaSessionManager mediaSessionManager = (MediaSessionManager) context.getSystemService(Service.MEDIA_SESSION_SERVICE);
        try {
            Class OnVolumeKeyLongPressListener = Class.forName("android.media.session.MediaSessionManager$OnVolumeKeyLongPressListener");
            Method setOnVolumeKeyLongPressListener = mediaSessionManager.getClass().getMethod("setOnVolumeKeyLongPressListener", OnVolumeKeyLongPressListener, Handler.class);
            setOnVolumeKeyLongPressListener.invoke(mediaSessionManager, listener, new Handler());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
//调用
        MediaKeyUtils.setVolumeKeyLongPressListener(this, new MediaSessionManager$OnVolumeKeyLongPressListener() {
            @Override
            public void onVolumeKeyLongPress(KeyEvent event) {
                if (event.getRepeatCount() == 0) {
                    int action = event.getAction();
                    if (action == KeyEvent.ACTION_DOWN) {
                        Log.i(TAG, "音量键按下");
                    } else if (action == KeyEvent.ACTION_UP) {
                        Log.i(TAG, "音量键松开");
                    }
                }
            }
        });

Guess you like

Origin blog.csdn.net/zzmzzff/article/details/130511830