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

發佈留言