在清單文件AndroidManifest.xml中添加權限:
<!-- 在SDCard中建立與刪除文件權限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard寫入數據權限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<!-- 訪問internet權限 -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
2. 具體實現代碼:
public class PhoneListenerService extends Service {
@Override
public void onCreate() {
TelephonyManager manager =
(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//監聽電話的狀態
manager.listen(new MyListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
private final class MyListener extends PhoneStateListener {
private String num;
private MediaRecorder recorder;
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING: /* 電話進來時 */
num = incomingNumber;
break;
case TelephonyManager.CALL_STATE_OFFHOOK: /* 接起電話時 */
try {
File file = new File(Environment.getExternalStorageDirectory(), num + "_" + System.currentTimeMillis() + ".3gp");
recorder = new MediaRecorder();
recorder.setAudioSource(AudioSource.MIC);//聲音採集來源(話筒)
recorder.setOutputFormat(OutputFormat.THREE_GPP);//輸出的格式
recorder.setAudioEncoder(AudioEncoder.AMR_NB);//音頻編碼方式
recorder.setOutputFile(file.getAbsolutePath());//輸出方向
recorder.prepare();
recorder.start();
} catch (Exception e) {
e.printStackTrace();
}
break;
case TelephonyManager.CALL_STATE_IDLE: /* 無任何狀態時 */
if (recorder != null) {
recorder.stop();
recorder.release();
}
break;
}
}
}
}