我使用过此代码,适用于Android 5.1(MotoE和MotoX以及另外1台设备)和8.1.0(诺基亚6)但不适用于8.0(One Plus 5)和7.0(MotoG5)。
new Thread(new Runnable() {
@Override
public void run() {
try {
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
//recorder.setAudioEncodingBitRate(320000);
//recorder.setAudioSamplingRate(44100);
} catch (Exception e) {
e.printStackTrace();
}
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/AutoCallPicker/PhoneCallRecord/");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
//String file_name = "Record";
String file_name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());//Naming according to date and time
try {
audioFile = File.createTempFile(file_name, ".amr",
sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
//Set output file .
recorder.setOutputFile(audioFile.getAbsolutePath());
//String formattedMessage[] = audioFile.getAbsolutePath().split(Commands.SPLIT_BY_SLASH);
//fileNameRecordedCall = formattedMessage[formattedMessage.length - 1].toString();
try {
//Call prepare before start().
recorder.prepare();
//Start recording .
recorder.start();
recordStarted = true;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
授予权限
<!-- Calling permission -->
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- permission to write on external storage -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我还使用了设备策略管理器,并按照以下链接的接受回答中提到的设备管理员 How to record phone calls in android?
但是这个东西对任何设备都不起作用。请帮助我缺少什么设置。