BroadcastReceiver实现android来去电录音功能(外录)

2019-04-14 08:15发布

因为原生android没有提供来去电内录功能,所以只能通过麦克进行通话录音,
/** * 来去电录音,因为去电没有接听的状态,只要拨出就会开始录音 * * @author jaeuken * @date 2015-1-4 */ public class PhoneBroadcastReceiver extends BroadcastReceiver { private static String outgoingNumber = ""; private static String incomeNumber = ""; private String state = ""; private static MediaRecorder mediaRecorder; @Override public void onReceive(Context context, Intent intent) { /*去电时: * 未接:phone_state=OFFHOOK; * 挂断:phone_state=IDLE * 来电时: * * 未接:phone_state=RINGING * 已接:phone_state=OFFHOOK; * 挂断:phone_state=IDLE**/ //如果是拨打电话 if(intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){ outgoingNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); } if(intent.getAction().equals("android.intent.action.PHONE_STATE")){ state = intent.getStringExtra(TelephonyManager.EXTRA_STATE); if("RINGING".equals(state)){ incomeNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); } if("OFFHOOK".equals(state)){//来电接通或去电(无法判断是否接通),开始录音 Thread recordingThread = new Thread() { @Override public void run() { try { File dirFile = Environment.getExternalStorageDirectory(); File file; //根据用来电号码是否为空判断来去电 if(incomeNumber!=null&&incomeNumber.length()>0){ file = new File(dirFile, "IN_"+incomeNumber +"_" + System.currentTimeMillis() + ".3gp"); }else{ file = new File(dirFile, "OUT_"+outgoingNumber +"_" + System.currentTimeMillis() + ".3gp"); } mediaRecorder = new MediaRecorder(); mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //获得声音数据源 mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 按3gp格式输出 mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); mediaRecorder.setOutputFile(file.getAbsolutePath()); //输出文件 mediaRecorder.prepare(); mediaRecorder.start(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } //准备 } }; recordingThread.start(); } if("IDLE".equals(state)){//挂断,停止录音 if(mediaRecorder != null){ mediaRecorder.stop(); mediaRecorder.reset(); mediaRecorder.release(); mediaRecorder = null; outgoingNumber = ""; incomeNumber = ""; } } } } }
需要的权限配置