当前位置:操作系统 > 安卓/Android >>

android 之service实现易做图听并录音

要实现易做图听,需要监听电话的状态,方法如下.

 


ListenReceiver类:   收到电话广播时开启监听电话的服务


public class ListenReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {
        context.startService(new Intent(context,ListenService.class));//收到广播时开启监听电话的服务
         }
}

 


ListenService类: 监听电话呼叫的状态,并在对应的状态进行响应的处理:


public class ListenService extends Service {

    public IBinder onBind(Intent intent) {
        return null;
    }

   
    public void onCreate() {
        System.out.println("开始监听电话服务状态");
        //获得电话管理器
        TelephonyManager manager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        //为管理器设置易做图,监听电话的呼叫状态
        manager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }
   
   
    private class MyPhoneListener extends  PhoneStateListener{
        private String num;//记录来电号码
        private MediaRecorder mRecorder;
        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
            case TelephonyManager.CALL_STATE_RINGING://来电振动
                num = incomingNumber;
                break;
            case TelephonyManager.CALL_STATE_OFFHOOK:// 当接通电话开始通话时  可以进行录音
                mRecorder = new MediaRecorder();
                mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); //此处只实现了录本地MIC输入的声音,若想录入对立通话者的声音
                mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
                mRecorder.setOutputFile("/mnt/sdcard/"+num+"_"+System.currentTimeMillis()+".3gp");
                mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                try {
                    mRecorder.prepare();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mRecorder.start();
               
                break;
            case TelephonyManager.CALL_STATE_IDLE://挂断电话时停止录音
                if(mRecorder!=null){
                mRecorder.stop(); //停止
                mRecorder.release();//释放
                mRecorder=null;//垃圾回收
                }
                break;
            }
        }
    }
}

 


//监听电话的状态

telManager.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);

 


在清单文件AndroidManifest.xml中添加权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

 

作者:t12x3456
补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,