简体   繁体   中英

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();
}

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);

    }
}

Check The For Run Time Permission

With Devices Higher OS than Android L Some Extra Features Are Available For Security Purpose. You Have To Check Some Risky Permission Again At Run time If They Are Not Given By User Then You Have To Ask To Grant It.

For More Look At Requesting Permission At Run Time

Officially from Android documentation :

Caution: You must either catch or pass IllegalArgumentException and IOException when using setDataSource(), because the file you are referencing might not exist

Make sure that the audio file exist and both Runtime Permission (For Api 23+) and Manifest permission is declared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM