Johnny Haliday Johnny Haliday - 1 year ago 74
Android Question

Android Permissions won't work

I'm trying to record a sound in java in android but the app crashes with this exception:


E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.example.mathieu.telefony1, PID: 31353
java.lang.RuntimeException: setAudioSource failed.


But it is very strange, because I added it to the AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application...


and here is my code to record a sound:

MediaRecorder mr = new MediaRecorder();
File file = new File(OUTPUT_FILE);
try {

mr.setOutputFile(OUTPUT_FILE);
mr.setAudioSource(MediaRecorder.AudioSource.MIC);
mr.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mr.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mr.prepare();
mr.start();
Thread.sleep(1000);
mr.stop();


} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}

Answer Source

Above API level 23 you will be given permission pragmatically like:

 private static final int PERMISSION_REQUEST_CODE = 1;

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {

    if (checkSelfPermission(Manifest.permission.SEND_SMS)
            == PackageManager.PERMISSION_DENIED) {

        Log.d("permission", "permission denied to SEND_SMS - requesting it");
        String[] permissions = {Manifest.permission.SEND_SMS};

        requestPermissions(permissions, PERMISSION_REQUEST_CODE);

    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download