這是我目前最好的解決方案。沒有辦法監聽請求麥克風的其他應用程序,因此我創建了一個每3秒運行一次的UsageStats
檢查器,以查看當前打開的應用程序是否有能力請求音頻。請讓我知道,如果你有更好的東西或改善這一點。
注:必須將權限添加到應用程序清單:
<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);
你有一個解決方案,我奮力爲 –
@KareemElsayed我貼我的最佳解決方案 – HaydenKai