业务逻辑:
当有电话打进来或电话打出去的时候,对电话进行录音。
public class TelphoneyListenerService extends Service {
private static final String TAG = "TelphoneyListenerService";
MediaRecorder mediaRecorder = null;
TelephonyManager tm = null;
MyListener myListener = null; @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
} @Override
public void onCreate() {
super.onCreate();
tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
myListener = new MyListener();
tm.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "服务启动成功", Toast.LENGTH_LONG).show();
return super.onStartCommand(intent, flags, startId);
} @Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "电话监听服务一停止"); Intent intent = new Intent(this, TelphoneyListenerService1.class);
startService(intent); tm.listen(myListener,PhoneStateListener.LISTEN_NONE);
myListener = null;
} private class MyListener extends PhoneStateListener {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (mediaRecorder != null) {
mediaRecorder.stop();
mediaRecorder.release();
mediaRecorder = null;
Log.i(TAG, "录音结束");
//把录音后的音频文件发送给服务端
}
break;
case TelephonyManager.CALL_STATE_RINGING:
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
//1、开启录音功能
Log.i(TAG, "开始录音");
mediaRecorder = new MediaRecorder();
//2、设置录音源头
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
//3、设置输出文件格式
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
//4、设置输出文件名
File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".3gp");
mediaRecorder.setOutputFile(file.getAbsolutePath());
//5、设置编码格式
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
//6、准备
mediaRecorder.prepare();
//7、开始
mediaRecorder.start(); break;
} } catch (Exception e) {
e.printStackTrace();
}
}
}
}