本文共 3224 字,大约阅读时间需要 10 分钟。
package com.itheima.recorder;
import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void click(View v){ Intent intent = new Intent( this, RecorderService. class ); startService(intent); } }
package com.itheima.recorder;import java.io.IOException;import android.app.Service;import android.content.Intent;import android.media.MediaRecorder;import android.os.IBinder;import android.telephony.PhoneStateListener;import android.telephony.TelephonyManager;public class RecorderService extends Service { private MediaRecorder recorder;//录音api @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); //拿到电话管理器 TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); //监听电话状态 //events:决定PhoneStateListener侦听什么内容 tm.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE); } class MyListener extends PhoneStateListener{ //一旦电话状态改变,此方法调用 @Override public void onCallStateChanged(int state, String incomingNumber) { super.onCallStateChanged(state, incomingNumber); switch (state) { case TelephonyManager.CALL_STATE_IDLE: System.out.println("空闲"); if(recorder != null){ recorder.stop(); recorder.release();//使用硬件录音是用c语言占用资源是不会自动释放的需要手动释放 recorder = null; } break; case TelephonyManager.CALL_STATE_RINGING: System.out.println("响铃"); if(recorder == null){ recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//音频来源麦克风 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setOutputFile("sdcard/luyin.3gp");//输出文件路径 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);//设置音频编码 try { recorder.prepare(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } break; case TelephonyManager.CALL_STATE_OFFHOOK: System.out.println("摘机"); //开始录音 if(recorder != null){ recorder.start(); } break; } } }}
读取电话状态 写sd卡权限 获取开机启动 开机广播接收者
本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/4948835.html,如需转载请自行联系原作者