Android 13 全局监听播放器暂停与播放 (包含系统层和第三方app)

首先设置监听:

说明:这里的代码屏蔽了系统层提示音播放暂停

     AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        manager.registerAudioPlaybackCallback(new AudioPlaybackCallback() {
            @Override
            public void onPlaybackConfigChanged(List configs) {
                super.onPlaybackConfigChanged(configs);
                boolean isPlayer = false;
                for (int i = 0; i < configs.size(); i++) {
                    int clientPid = configs.get(i).getClientPid();
                    int systempid = getSystemPID();
                    Log.d("播放pid:" + clientPid);
                    Log.d("系统pid:" + systempid);
                    if (systempid == clientPid) continue;
                    if (configs.get(i).isActive()) {
                        isPlayer = true;
                        break;
                    }
                }

                if (isPlayer) {
                    //开始本地播放
                    Log.d("开始本地播放");
                    updatePlayModeAnim(SWITCH_LOCAL_MODE);
                } else {
                    Log.d("停止本地播放");
                }
            }
        }, new Handler());

获取系统pid判断是否是系统层提示音播放暂停

    private int systemPID = -1;

    private int getSystemPID() {
        if (systemPID >= 0) return systemPID;
        int pid = -1;
        ActivityManager am = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        List mRunningProcess = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess) {
            if (!TextUtils.isEmpty(amProcess.processName) && TextUtils.equals("system", amProcess.processName)) {
                pid = amProcess.pid;
                break;
            }
        }
        return pid;
    }

你可能感兴趣的:(android)