- 来电状态监听
public class MyService extends Service { private MediaRecorder mRecorder; private String num; @Override public void onCreate() { super.onCreate(); TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); // 获取电话管理器 manager.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE); // 监听电话状态 } private class MyPhoneStateListener extends PhoneStateListener { // 电话状态监听器 public void onCallStateChanged(int state, String incomingNumber) { // 在电话状态改变时执行 switch (state) { case TelephonyManager.CALL_STATE_RINGING: // 振铃 System.out.println("来电话了"); num = incomingNumber;//得到来电号码 break; case TelephonyManager.CALL_STATE_OFFHOOK: // 摘机 System.out.println("开始通话"); start(); break; case TelephonyManager.CALL_STATE_IDLE: // 空闲 System.out.println("挂断电话"); stop(); break; } } } public void onDestroy() { tm.listen(listener, PhoneStateListener.LISTEN_NONE);// 取消监听 listener = null; }
- 录音
private void start() { mRecorder = new MediaRecorder(); // 创建媒体记录器 mRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); // 指定音频源(麦克风) mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); // 设置输出格式(3gp) mRecorder.setOutputFile("/mnt/sdcard/" + num + "-" + System.currentTimeMillis() + ".3gp"); // 指定文件路径(SD卡) mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); // 指定编码(AMR_NB) try { mRecorder.prepare(); // 准备 } catch (Exception e) { e.printStackTrace(); } mRecorder.start(); // 开始 } @Override public IBinder onBind(Intent intent) { return null; } //下面是录音 private void stop() { if (mRecorder != null) { mRecorder.stop(); // 停止 mRecorder.release(); // 释放 mRecorder = null; // 垃圾回收 } }