packagexidian.dy.com.chujia;importandroid.app.Service;importandroid.content.Intent;importandroid.media.MediaRecorder;importandroid.os.Environment;importandroid.os.IBinder;importandroid.support.annotation.Nullable;importandroid.telephony.PhoneStateListener;importandroid.telephony.TelephonyManager;importandroid.util.Log;importjava.io.IOException;/*** Created by dy on 2016/7/12.*/
public class MyService extendsService {
TelephonyManager tm;
@Overridepublic voidonCreate() {super.onCreate();//获取电话管理器
tm =(TelephonyManager) getSystemService(TELEPHONY_SERVICE);//对感兴趣的事件进行监听,传入回调函数
tm.listen(newMyListener(),PhoneStateListener.LISTEN_CALL_STATE);
}class MyListener extendsPhoneStateListener{
MediaRecorder mRecorder;//一旦电话状态改变该方法被调用
@Overridepublic void onCallStateChanged(intstate, String incomingNumber) {super.onCallStateChanged(state, incomingNumber);switch(state){//电话处于空闲状态停止录音
caseTelephonyManager.CALL_STATE_IDLE:if(mRecorder != null){
mRecorder.stop();
mRecorder.release();
mRecorder= null;
}break;//电话处于响铃状态
caseTelephonyManager.CALL_STATE_RINGING:
mRecorder= newMediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(Environment.getExternalStorageDirectory().toString()+ "/record.3gp");
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);try{
mRecorder.prepare();
}catch(IOException e) {
Log.e(this.getClass().getName(), "prepare() failed");
}break;//电话处于摘机状态
caseTelephonyManager.CALL_STATE_OFFHOOK:if(mRecorder != null){
mRecorder.start();
}break;
}
}
}
@Nullable
@OverridepublicIBinder onBind(Intent intent) {return null;
}
}