Android 來去電自動錄音實戰:從通話狀態監聽到錄音落地
日常使用 Android 手機通話時,我們偶爾會有把來電、去電全程錄下來的需求——不管是為了留存重要通話記錄,還是方便事後複核內容。本文就帶大家一步步動手,把「來去電自動錄音」這個功能真正做出來。只要跟著文中的思路把程式碼敲一遍,你就能掌握其中的關鍵。
整個功能的靈魂,在於準確捕捉手機電話狀態的每一次切換。
先來理清通話狀態的變化脈絡。
來電的狀態流轉是這樣的(我們真正要用到的是其中幾個節點):
空閒(IDLE)→ 響鈴(RINGING)→ 接聽(ACTIVE)→ 掛斷(先經歷 DISCONNECTING,再到 DISCONNECTED)→ 空閒(IDLE);
再比如來電被拒接的情況:空閒(IDLE)→ 響鈴(RINGING)→ 拒接 → 空閒(IDLE)。
去電的狀態流轉則稍複雜一些:
空閒(IDLE)→ 撥號(DIALING)→ 對方響鈴(ALERTING)→ 建立連接(ACTIVE)→ 掛斷(DISCONNECTING → DISCONNECTED)→ 空閒(IDLE);
若對方一直沒接:空閒(IDLE)→ 撥號(DIALING)→ 對方響鈴(ALERTING)→ 掛斷或對方拒接 → 空閒(IDLE)。
下面我們就分來電、去電兩條線,逐一拆解並實現。
一、來電自動錄音的實現
相比去電,來電的狀態檢測要簡單得多。Android API 中的 PhoneStateListener 類已經提供了現成的方法,我們只需覆寫其中的 onCallStateChanged(int state, String incomingNumber),就能拿到來電狀態的變化,再在此基礎上掛上錄音邏輯即可。
其中的 state 參數代表各種電話狀態,我們把它和感興趣的狀態做比對,命中就執行相應操作,否則忽略。要拿到這些狀態,還需要另一個關鍵類 TelephonyManager,它提供了豐富的電話狀態常量,這裡我們主要用到三個:CALL_STATE_IDLE(空閒)、CALL_STATE_OFFHOOK(摘機接通)與 CALL_STATE_RINGING(來電響鈴)。繼承 android.telephony.PhoneStateListener 並實作上述方法,代碼如下:
- public class TelListener extends PhoneStateListener {
-
- @Override
- public void onCallStateChanged(int state, String incomingNumber) {
- super.onCallStateChanged(state, incomingNumber);
-
- switch (state) {
- case TelephonyManager.CALL_STATE_IDLE: // 空閒狀態,即無來電也無去電
- Log.i("TelephoneState", "IDLE");
- //此處添加一系列功能代碼
- break;
- case TelephonyManager.CALL_STATE_RINGING: // 來電響鈴
- Log.i("TelephoneState", "RINGING");
- //此處添加一系列功能代碼
- break;
- case TelephonyManager.CALL_STATE_OFFHOOK: // 摘機,即接通
- Log.i("TelephoneState", "OFFHOOK");
- //此處添加一系列功能代碼
- break;
- }
-
- Log.i("TelephoneState", String.valueOf(incomingNumber));
- }
-
- }
光有監聽類還不夠,我們還得在某個 Activity 或 Service 裡把它掛起來。做法很簡單:
- /**
- * 在activity 或者 service中加入如下代碼,以實現來電狀態監聽
- */
- TelephonyManager telMgr = (TelephonyManager)context.getSystemService(
- Context.TELEPHONY_SERVICE);
- telMgr.listen(new TelListener(), PhoneStateListener.LISTEN_CALL_STATE);
這樣監聽就跑起來了。不過要在真機上正常工作,還得在清單檔裡補上讀取電話狀態的權限:
- <uses-permission android:name="android.permission.READ_PHONE_STATE" />
- <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
說到這裡,只要你已經能實現基本的錄音功能,把它嫁接到來電場景其實水到渠成。思路很直白:監聽到 CALL_STATE_OFFHOOK(接通)時啟動錄音,監聽到 CALL_STATE_IDLE(掛斷回到空閒)時停止錄音。這樣來電自動錄音就成型了。別忘了錄音與檔案讀寫同樣需要相應權限:
- <uses-permission android:name="android.permission.RECORD_AUDIO"/>
-
- <!-- 要存儲文件或者創建文件夾的話還需要以下兩個權限 -->
- <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
- <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
二、去電自動錄音的實現
講完來電,再來看看麻煩一些的去電。之所以說麻煩,是因為 Android API 並沒有直接提供去電狀態的監聽類和方法。一開始我也上網搜了一圈,結果大多數方案都是講來電監聽的。中途翻到一篇提到「查詢系統日誌」的博文(可惜後來再也搜不到了),思路是從 logcat 日誌裡抓取去電過程中各個狀態的關鍵詞。無奈之下,最終採用了這個方案。
以下是我在聯想 A65 上抓到的去電日誌,過濾關鍵詞為 mforeground:
- 01-06 16:29:54.225: D/InCallScreen(251): onPhoneStateChanged: mForegroundCall.getState() : DIALING
- 01-06 16:29:54.245: V/LogInfo OutGoing Call(2492): D/InCallScreen( 251): onPhoneStateChanged: mForegroundCall.getState() : DIALING
- 01-06 16:29:57.030: D/InCallScreen(251): onPhoneStateChanged: mForegroundCall.getState() : ACTIVE
- 01-06 16:29:59.319: D/InCallScreen(251): onPhoneStateChanged: mForegroundCall.getState() : DISCONNECTING
- 01-06 16:30:00.392: D/InCallScreen(251): - onDisconnect: currentlyIdle:true ; mForegroundCall.getState():DISCONNECTED
- 01-06 16:30:01.042: D/InCallScreen(251): onPhoneStateChanged: mForegroundCall.getState() : IDLE
對應的後台通話狀態(過濾 mbackground)始終為 IDLE,這裡從略。仔細觀察可以發現,每行末尾那個大寫英文單詞,就是去電的狀態:
DIALING:正在撥號,對方還未響鈴;
ALERTING:對方正在響鈴;
ACTIVE:對方已接通,通話建立;
DISCONNECTING:通話正在斷開;
DISCONNECTED:通話已斷開,相當於掛機。
由於我撥的是 10010,電腦自動接通得太快,日誌裡少了 ALERTING 這個「對方響鈴」的環節。
掌握了這幾個狀態就好辦了。接下來要做的,就是讀取系統日誌、找到這些狀態並提取出來。關鍵詞就是前面提到的 mforeground(前台通話狀態)與 mbackground(後台通話狀態)——不同設備生成的日誌格式可能不同,需按自己的實機調整,這裡只提取前台狀態。判斷邏輯是:若某行日誌包含 mforeground,再看它是否包含上述狀態單詞。具體讀取日誌的程式碼如下。
- package com.sdvdxl.phonerecorder;
-
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
-
- import com.sdvdxl.outgoingcall.OutgoingCallState;
-
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
-
- public class ReadLog extends Thread {
- private Context ctx;
- private int logCount;
- private static final String TAG = "LogInfo OutGoing Call";
- private static class CallViewState {
- public static final String FORE_GROUND_CALL_STATE = "mForeground";
- }
- private static class CallState {
- public static final String DIALING = "DIALING";
- public static final String ALERTING = "ALERTING";
- public static final String ACTIVE = "ACTIVE";
- public static final String IDLE = "IDLE";
- public static final String DISCONNECTED = "DISCONNECTED";
- }
- public ReadLog(Context ctx) {
- this.ctx = ctx;
- }
- @Override
- public void run() {
- Log.d(TAG, "開始讀取日誌記錄");
- String[] catchParams = {"logcat", "InCallScreen *:s"};
- String[] clearParams = {"logcat", "-c"};
- try {
- Process process=Runtime.getRuntime().exec(catchParams);
- InputStream is = process.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- String line = null;
- while ((line=reader.readLine())!=null) {
- logCount++;
- Log.v(TAG, line);
- if (logCount>512) {
- Runtime.getRuntime().exec(clearParams).destroy();
- logCount = 0;
- }
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.IDLE)) {
- Log.d(TAG, ReadLog.CallState.IDLE);
- }
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.DIALING)) {
- Log.d(TAG, ReadLog.CallState.DIALING);
- }
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.ALERTING)) {
- Log.d(TAG, ReadLog.CallState.ALERTING);
- }
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.ACTIVE)) {
- Log.d(TAG, ReadLog.CallState.ACTIVE);
- }
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.DISCONNECTED)) {
- Log.d(TAG, ReadLog.CallState.DISCONNECTED);
- }
- } //END while
- } catch (IOException e) {
- e.printStackTrace();
- } //END try-catch
- } //END run
- } //END class ReadLog
這裡之所以要用獨立的執行緒,是為了避免讀日誌的過程阻塞主執行緒,進而影響程式即時捕捉電話狀態。
捕捉到去電的各個狀態後,如何把結果通知給程式呢?我採用的辦法是:一旦捕獲到狀態就立刻發送一條廣播,由程式接收後再處理錄音。為了發送唯一的廣播,先建立如下類:
- package com.sdvdxl.outgoingcall;
- import android.content.Context;
- import android.util.Log;
- public class OutgoingCallState {
- Context ctx;
- public OutgoingCallState(Context ctx) {
- this.ctx = ctx;
- }
- public static final class ForeGroundCallState {
- public static final String DIALING = "com.sdvdxl.phonerecorder.FORE_GROUND_DIALING";
- public static final String ALERTING = "com.sdvdxl.phonerecorder.FORE_GROUND_ALERTING";
- public static final String ACTIVE = "com.sdvdxl.phonerecorder.FORE_GROUND_ACTIVE";
- public static final String IDLE = "com.sdvdxl.phonerecorder.FORE_GROUND_IDLE";
- public static final String DISCONNECTED = "com.sdvdxl.phonerecorder.FORE_GROUND_DISCONNECTED";
- }
- public void startListen() {
- new ReadLog(ctx).start();
- Log.d("Recorder", "開始監聽呼出狀態的轉變,並在對應狀態發送廣播");
- }
- }
讀取系統日誌需要相應權限:
- <uses-permission android:name="android.permission.READ_LOGS" />
接著,在讀取日誌的類裡,每檢測到一個去電狀態就發送對應廣播。加入廣播發送後的 ReadLog 完整程式碼如下(在每個狀態判斷分支中補上 sendBroadcast 即可):
- // 以 ACTIVE 狀態為例,其餘狀態同理
- if (line.contains(ReadLog.CallViewState.FORE_GROUND_CALL_STATE) && line.contains(ReadLog.CallState.ACTIVE)) {
- Intent intent = new Intent();
- intent.setAction(OutgoingCallState.ForeGroundCallState.ACTIVE);
- ctx.sendBroadcast(intent);
- Log.d(TAG, ReadLog.CallState.ACTIVE);
- }
有了發送方,自然也要有接收方。自訂廣播接收者如下(錄音機相關程式碼可先略過):
- package com.sdvdxl.phonerecorder;
- import android.content.BroadcastReceiver;
- import android.content.Context;
- import android.content.Intent;
- import android.util.Log;
- import com.sdvdxl.outgoingcall.OutgoingCallState;
- public class OutgoingCallReciver extends BroadcastReceiver {
- static final String TAG = "Recorder";
- private MyRecorder recorder;
- public OutgoingCallReciver() {
- recorder = new MyRecorder();
- }
- public OutgoingCallReciver(MyRecorder recorder) {
- this.recorder = recorder;
- }
- @Override
- public void onReceive(Context ctx, Intent intent) {
- String phoneState = intent.getAction();
- if (phoneState.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
- String phoneNum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);//撥出號碼
- recorder.setPhoneNumber(phoneNum);
- recorder.setIsCommingNumber(false);
- }
- if (phoneState.equals(OutgoingCallState.ForeGroundCallState.ACTIVE)) {
- if (!recorder.isCommingNumber() && !recorder.isStarted()) {
- recorder.start(); //去電已接通,啟動錄音機
- }
- }
- if (phoneState.equals(OutgoingCallState.ForeGroundCallState.DISCONNECTED)) {
- if (!recorder.isCommingNumber() && recorder.isStarted()) {
- recorder.stop(); //已掛斷,關閉錄音機
- }
- }
- }
- }
其中這段程式碼接收的是系統發出的去電廣播,藉此拿到去電號碼並標記為去電狀態:
- String phoneState = intent.getAction();
- if (phoneState.equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
- String phoneNum = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);//撥出號碼
- recorder.setPhoneNumber(phoneNum);
- recorder.setIsCommingNumber(false);
- }
三、用 Service 統一承載監聽邏輯
有了上面這些核心程式碼,來去電監聽可說已經成型。接下來建立一個 Service 來統一運行監聽:
- package com.sdvdxl.service;
- import android.app.Service;
- import android.content.Context;
- import android.content.Intent;
- import android.content.IntentFilter;
- import android.os.IBinder;
- import android.telephony.PhoneStateListener;
- import android.telephony.TelephonyManager;
- import android.util.Log;
- import android.widget.Toast;
- import com.sdvdxl.outgoingcall.OutgoingCallState;
- import com.sdvdxl.phonerecorder.MyRecorder;
- import com.sdvdxl.phonerecorder.OutgoingCallReciver;
- import com.sdvdxl.phonerecorder.TelListener;
- public class PhoneCallStateService extends Service {
- private OutgoingCallState outgoingCallState;
- private OutgoingCallReciver outgoingCallReciver;
- private MyRecorder recorder;
- @Override
- public void onCreate() {
- super.onCreate();
- recorder = new MyRecorder();
- outgoingCallState = new OutgoingCallState(this);
- outgoingCallReciver = new OutgoingCallReciver(recorder);
- outgoingCallState.startListen();
- Toast.makeText(this, "服務已啟動", Toast.LENGTH_LONG).show();
- //去電:註冊廣播接收者
- IntentFilter filter = new IntentFilter();
- filter.addAction(OutgoingCallState.ForeGroundCallState.IDLE);
- filter.addAction(OutgoingCallState.ForeGroundCallState.DIALING);
- filter.addAction(OutgoingCallState.ForeGroundCallState.ALERTING);
- filter.addAction(OutgoingCallState.ForeGroundCallState.ACTIVE);
- filter.addAction(OutgoingCallState.ForeGroundCallState.DISCONNECTED);
- filter.addAction("android.intent.action.PHONE_STATE");
- filter.addAction("android.intent.action.NEW_OUTGOING_CALL");
- registerReceiver(outgoingCallReciver, filter);
- //來電
- TelephonyManager telmgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
- telmgr.listen(new TelListener(recorder), PhoneStateListener.LISTEN_CALL_STATE);
- }
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
- unregisterReceiver(outgoingCallReciver);
- }
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- return START_STICKY;
- }
- }
別忘了在清單檔中註冊這個 Service:
- <service android:name="com.sdvdxl.service.PhoneCallStateService" />
四、錄音機的實現
至此,來去電狀態監聽已經全部搞定,最後只剩一個錄音機。核心是利用 MediaRecorder 錄音,並根據來電/去電標記自動歸檔。程式碼如下:
- package com.sdvdxl.phonerecorder;
- import java.io.File;
- import java.io.IOException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import android.media.MediaRecorder;
- import android.os.Environment;
- import android.util.Log;
- public class MyRecorder {
- private String phoneNumber;
- private MediaRecorder mrecorder;
- private boolean started = false;//錄音機是否已經啟動
- private boolean isCommingNumber = false;//是否是來電
- private String TAG = "Recorder";
- public void start() {
- started = true;
- mrecorder = new MediaRecorder();
- File recordPath = new File(Environment.getExternalStorageDirectory(), "/My record");
- if (!recordPath.exists()) {
- recordPath.mkdirs();
- }
- String callDir = "呼出";
- if (isCommingNumber) {
- callDir = "呼入";
- }
- String fileName = callDir + "-" + phoneNumber + "-" + new SimpleDateFormat("yy-MM-dd_HH-mm-ss").format(new Date(System.currentTimeMillis())) + ".mp3";
- File recordName = new File(recordPath, fileName);
- try {
- recordName.createNewFile();
- } catch (IOException e) {
- e.printStackTrace();
- }
- mrecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
- mrecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
- mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
- mrecorder.setOutputFile(recordName.getAbsolutePath());
- try {
- mrecorder.prepare();
- } catch (Exception e) {
- e.printStackTrace();
- }
- mrecorder.start();
- Log.d(TAG, "錄音開始");
- }
- public void stop() {
- try {
- if (mrecorder != null) {
- mrecorder.stop();
- mrecorder.release();
- mrecorder = null;
- }
- started = false;
- } catch (Exception e) {
- e.printStackTrace();
- }
- Log.d(TAG, "錄音結束");
- }
- // get/set 方法略
- }
至此,來去電通話自動錄音的全部功能就完成了。有興趣的朋友不妨動手實作一遍,把整個流程跑通,你會對 Android 的電話狀態機制與錄音速記有更透徹的體會。