检测是否有其他应用正在请求麦克风

问题描述 投票:2回答:1

我已经看到有关SO的多个问题,说不可能看到另一个应用程序何时想要使用麦克风(Unable to access microphone when another app is using it in Android)。但是,我知道这是可能的,因为Shazam有一个“自动”功能,允许我想要的确切功能:当其他应用程序不使用麦克风时持续听音频。

目前,当我使用我的应用程序并使用像Snapchat这样的应用程序时,我无法录制带有音频的视频,因为Snapchat不接受麦克风。但是,正如我之前所说,在这种情况下,Shazam的Auto功能正常。

那么当其他应用想要使用麦克风时,我该如何收听呢?只要它不需要生根电话或类似设备,我就可以使用“hack”。

编辑:Shazam从来没有这个功能,他们的应用程序无法在运行时将麦克风放弃到其他应用程序。

android audio-recording
1个回答
1
投票

这是我目前最好的解决方案。无法监听请求麦克风的其他应用程序,因此我创建了一个UsageStats检查程序,每3秒运行一次,以查看当前打开的应用程序是否具有请求音频的能力。如果您有更好的事情或对此进行改进,请告诉我。

注意:您必须将权限添加到应用清单:

<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />

    AppOpsManager appOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
    int mode = appOps.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
            android.os.Process.myUid(), getPackageName());

    if (mode != AppOpsManager.MODE_ALLOWED) {
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        startActivity(intent);
    }

    if (otherAppAudioTimer != null) {
        otherAppAudioTimer.cancel();
    }

    otherAppAudioTimer = new Timer();
    otherAppAudioTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            UsageStatsManager usm = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            long now = System.currentTimeMillis();
            final List<UsageStats> queryUsageStats = usm.queryUsageStats(UsageStatsManager.INTERVAL_YEARLY, now - (1000 * 60 * 60), now);
            if (queryUsageStats != null && queryUsageStats.size() > 0) {
                SortedMap<Long, UsageStats> mySortedMap = new TreeMap<>();
                for (UsageStats usageStats : queryUsageStats) {
                    mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
                }
                if (!mySortedMap.isEmpty()) {
                    String currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
                    boolean hasRecordAudio = getPackageManager()
                            .checkPermission(Manifest.permission.RECORD_AUDIO, currentApp)
                            == PackageManager.PERMISSION_GRANTED;

                    if (getApplicationContext().getPackageName().equals(currentApp)) {
                        Log.e("hasAudio", "Current app is self");
                        return;
                    }


                    if (hasRecordAudio) {
                        //the current app can record audio
                    } else {
                        //the current app cannot record audio
                    }

                }
            }
        }
    }, 0, 3000);
© www.soinside.com 2019 - 2024. All rights reserved.