1、继承Service类
2、在清单文件进行配置(因为Service属于四大组件之一)
<service android:name=".PhoneStatusService"> </service>
3、因为要监听电话状态,并且把文件存在外存中,所以权限配置为
1 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 2 <uses-permission android:name="android.permission.RECORD_AUDIO"/> 3 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
4、开启一个服务的代码(像activity、broadcastReceive都使用intent进行开启)
1 //开启服务 2 Intent intent = new Intent(this, PhoneStatusService.class); 3 startService(intent);
5、通过媒体监听电话情况的Service的代码
1 package com.example.callstatuslistener; 2 3 import java.io.IOException; 4 5 import android.app.Service; 6 import android.content.Intent; 7 import android.media.MediaRecorder; 8 import android.os.IBinder; 9 import android.telephony.PhoneStateListener; 10 import android.telephony.TelephonyManager; 11 /** 12 * @desc 服务一旦被开启,则会长期运行在后台,除非手工停止掉 13 * @author zyh 14 * 15 */ 16 public class PhoneStatusService extends Service { 17 //服务被创建了 18 @Override 19 public void onCreate() { 20 // TODO Auto-generated method stub 21 super.onCreate(); 22 System.out.println("服务开启"); 23 //电话管理器,它能够获取电话的各种信息 24 TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); 25 //监听手机的通话状态的变化 26 tm.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE); 27 } 28 29 private class MyPhoneListener extends PhoneStateListener{ 30 31 private MediaRecorder recorder; 32 @Override 33 public void onCallStateChanged(int state, String incomingNumber) { 34 // TODO Auto-generated method stub 35 super.onCallStateChanged(state, incomingNumber); 36 try { 37 switch(state){ 38 case TelephonyManager.CALL_STATE_IDLE: //空闲状态,也没有响铃 39 if(recorder != null){ //释放资源 40 recorder.stop(); 41 recorder.reset(); // You can reuse the object by going back to setAudioSource() step 42 recorder.release(); // Now the object cannot be reused 43 } 44 break; 45 case TelephonyManager.CALL_STATE_RINGING: //响铃状态 46 System.out.println("发现来电号码为:" + incomingNumber); 47 recorder = new MediaRecorder(); 48 //设置录制的音频源,从话筒中获取声音,只能录制自己的 49 recorder.setAudioSource(MediaRecorder.AudioSource.MIC); 50 //设置它的文件格式 51 recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); 52 //设置的音频的编码格式 53 recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); 54 //文件保存的位置 55 recorder.setOutputFile("/sdcard/" + System.currentTimeMillis() + ".3gp"); 56 recorder.prepare(); 57 58 break; 59 case TelephonyManager.CALL_STATE_OFFHOOK: //通话状态 60 if(recorder != null){ 61 recorder.start(); 62 } 63 break; 64 } 65 } catch (IOException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 } 70 71 } 72 73 //服务销毁了 74 @Override 75 public void onDestroy() { 76 // TODO Auto-generated method stub 77 super.onDestroy(); 78 System.out.println("服务销毁"); 79 } 80 81 @Override 82 public IBinder onBind(Intent intent) { 83 // TODO Auto-generated method stub 84 return null; 85 } 86 87 }
)