我按照Record phone calls on android phone?的示例並將其放在BroadcastReceiver上,以嘗試錄製MIC語音(我知道它仍限於記錄另一面)呼入和呼出。 我的問題是:如何獲取用戶拿起電話的狀態。因爲當它響起時,它也會轉到「android.intent.action.PHONE_STATE」的動作。當電話呼入或呼出時錄製語音(僅限MIC)
我的代碼:
public class PhoneCallReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (action.equals("android.intent.action.PHONE_STATE")
{
// Phone call recording
try {
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
recorder.setOutputFile(<my output dir>);
recorder.prepare();
recorder.start();
recordStarted = true;
telManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
} catch(Exception ex) {
}
}
}
}
private final PhoneStateListener phoneListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
try {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: {
//
break;
}
case TelephonyManager.CALL_STATE_OFFHOOK: {
//
break;
}
case TelephonyManager.CALL_STATE_IDLE: {
if (recordStarted) {
recorder.stop();
recordStarted = false;
}
break;
}
default: { }
}
} catch (Exception ex) {
}
}
};
在AndroidManifest.xml
<receiver android:name=".PhoneCallReceiver" android:enabled="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
代碼基於Android 2.1的SDK和HTC EVO 4G(Android 2.2的)測試
謝謝。但是我發現它觸發了TelephonyManager.CALL_STATE_OFFHOOK狀態,當我接聽電話並且intent.getAction()永遠不會成爲android.intent.action.ANSWER,但始終是android.intent.action.PHONE_STATE。順便說一句,我開發與2.1 SDK和測試它在Android 2.2(HTC EVO 4G) –