我正在开发一个应该有" RECORD_AUDIO"权限,但在实现以下代码后,对话框不显示。每当我手动进入设备上的应用程序设置以打开权限时,它都可以正常工作。
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] perms = {Manifest.permission.RECORD_AUDIO};
if (EasyPermissions.hasPermissions(this, perms)) {
initiateAudio();
// Already have permission, do the thing
// ...
} else {
// Do not have permissions, request them now
EasyPermissions.requestPermissions(this, "REQUEST_AUDIO",
1, perms);
}
}
private void initiateAudio(){
PitchDetectionHandler pdh = new PitchDetectionHandler() {
@Override
public void handlePitch(PitchDetectionResult result, AudioEvent e) {
final float pitchInHz = result.getPitch();
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView text = (TextView) findViewById(R.id.textView);
text.setText("" + pitchInHz);
}
});
}
};
AudioProcessor p = new PitchProcessor(PitchProcessor.PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(p);
new Thread(dispatcher,"Audio Dispatcher").start();
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
initiateAudio();
}
@Override
public void onPermissionsDenied(int requestCode, List<String> list) {
Toast.makeText(this, "Audio Permission not granted", Toast.LENGTH_LONG).show();
}
}
以下是清单的相关部分:
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="26" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
我在这里缺少一些简单的东西吗?
答案 0 :(得分:1)
我发现了问题所在:
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
在请求权限之后,需要调用,而不是之前。