Android–service服務–MediaRecorder–電話錄音

一、通過Intent啟動服務:

package com.jiangge.callstatuslistener;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Intent intent = new Intent(this, PhoneStatusService.class);
		startService(intent);
	}
}

二、PhoneStatusService.java

package com.jiangge.callstatuslistener;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

public class PhoneStatusService extends Service {

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

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("===>>>服務被創建瞭");
		TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		tm.listen(new MyPhoneStatusListener(), PhoneStateListener.LISTEN_CALL_STATE);// 監聽手機的通話狀態的變化
	}

	private class MyPhoneStatusListener extends PhoneStateListener {
		MediaRecorder recorder;
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			try {
				switch (state) {
				case TelephonyManager.CALL_STATE_IDLE: // 空閑狀態,沒有通話沒有響鈴
					if (recorder != null) {
						recorder.stop();
						recorder.reset();
						recorder.release();
						recorder = null;
					}
					break;
				case TelephonyManager.CALL_STATE_RINGING: // 響鈴狀態
					System.out.println("發現來電號碼" + incomingNumber);
					recorder = new MediaRecorder();// 創建一個錄音機
					recorder.setAudioSource(MediaRecorder.AudioSource.MIC);// 設置錄制的音頻源從話筒裡面獲取聲音
					recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
					recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
					recorder.setOutputFile("/sdcard/" + System.currentTimeMillis() + ".3gp");
					recorder.prepare();

					break;
				case TelephonyManager.CALL_STATE_OFFHOOK: // 通話狀態
					if (recorder != null) {
						recorder.start();
					}
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("===>>>服務被銷毀瞭");
	}

}

註:/sdcard 不要硬編碼

Do not hardcode “/sdcard/”; use Environment.getExternalStorageDirectory().getPath()instead

三、清單文件:



    
    
    
    

    
        
            
                

                
            
        

        
        
    

註,權限:

    
    
    

效果圖:

項目文件結構:

註:MediaRecZ喎?https://www.aiwalls.com/kf/ware/vc/” target=”_blank” class=”keylink”>vcmRlcs7EtbXW0NC0tcO63Mfls/61xKGjPC9wPgo8cD48aW1nIHNyYz0=”https://www.aiwalls.com/uploadfile/Collfiles/20131203/20131130230837906.jpg” alt=””>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *