android 通話錄音功能

m45y 9年前發布 | 5K 次閱讀 Java Android

一、監聽服務

    package com.newland.teleinterface;

import java.io.File;  
import java.io.IOException;  
import java.lang.reflect.Method;  
import java.util.Calendar;  

import com.android.internal.telephony.ITelephony;  

import android.content.Context;  
import android.content.Intent;  
import android.media.MediaRecorder;  
import android.net.Uri;  
import android.os.Environment;  
import android.os.Handler;  
import android.os.Message;  
import android.telephony.PhoneStateListener;  
import android.telephony.TelephonyManager;  
import android.util.Log;  
import android.widget.Toast;  

/** 
 *  
 * @author JD 功能:打電話,錄音,通話時間 
 *  
 */  
public class TeleInterface {  

  private String TAG = "TeleInterface";  
  private Context activity;  
  private Handler handler;  
  private Calendar calendar;  
  private String teleStartTime;  
  private String teleEndTime;  
  private TelephonyManager telephonyManager;  
  public static int TELE_START_TIME = 5;  
  public static int TELE_END_TIME = 6;  

  public String getTeleStartTime() {  
    return teleStartTime;  
  }  

  public String getTeleEndTime() {  
    return teleEndTime;  
  }  

  /** 
   * 構造函數 
   *  
   * @param activity 
   * @param handler 自定義handler接收消息 msg.what 5:電話撥通時間 6:電話掛斷時間 
   */  
  public TeleInterface(Context activity, Handler handler) {  
    this.activity = activity;  
    this.handler = handler;  
  }  

  /** 
   * 撥打電話 
   *  
   * @param phoneNum 需要撥打號碼 
   */  
  public void Call(String phoneNum) {  
    if (phoneNum.length() != 0) {  
      Intent phoneIntent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phoneNum));  
      activity.startActivity(phoneIntent);  
    } else {  
      Toast.makeText(activity, "不能輸入為空", Toast.LENGTH_LONG).show();  
    }  
  }  

  /** 
   * 來電監聽注冊 
   */  
  public void teleListen() {  
    telephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);// 注冊監聽器  

    telephonyManager.listen(new PhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);// 監聽電話狀態  
  }  

  /** 
   * 掛斷電話 
   *  
   * @throws Exception 
   */  
  public void endCall() throws Exception {  
    ITelephony iTelephony = PhoneUtils.getITelephony(telephonyManager);  
    iTelephony.endCall();// 自動掛斷電話  
  }  


  private final class PhoneListener extends PhoneStateListener {  
    private String incomeNumber; // 來電號碼  
    private MediaRecorder mediaRecorder;  
    private File root_file, file;  

    @Override  
    public void onCallStateChanged(int state, String incomingNumber) {  
      try {  
        switch (state) {  
          case TelephonyManager.CALL_STATE_RINGING: // 來電  
            this.incomeNumber = incomingNumber;  
            break;  
          case TelephonyManager.CALL_STATE_OFFHOOK: // 接通電話  
            calendar = Calendar.getInstance();  
            teleStartTime = calendar.getTime().toString();  

            String root_directory = Environment.getExternalStorageDirectory() + "/recorded_calls";  
            root_file = new File(root_directory);  
            if (!root_file.exists()) {  
              root_file.mkdir();  
            }  
            if(this.incomeNumber==null){  
                this.incomeNumber = "call";  
            }  
            String record_call =  
                root_directory + "/" + this.incomeNumber + "_" + System.currentTimeMillis()  
                    + ".amr";  
            file = new File(record_call);  
            if (!file.exists()) {  
              file.createNewFile();  
            }  

            mediaRecorder = new MediaRecorder();  
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL); // 獲得聲音數據源  
            mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT); // 格式輸出  
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);  
            mediaRecorder.setOutputFile(file.getAbsolutePath()); // 輸出文件  
            mediaRecorder.prepare(); // 準備  

            mediaRecorder.start();  

            Log.d(TAG, "開始錄音!");  

            Message msg_start = new Message();  
            msg_start.what = TELE_START_TIME;  
            msg_start.obj = teleStartTime;  

            Log.d(TAG, "StartTime=====" + teleStartTime);  

            handler.sendMessage(msg_start);  
            break;  

          case TelephonyManager.CALL_STATE_IDLE: // 掛掉電話  
            if (mediaRecorder != null) {  
              mediaRecorder.stop();  
              mediaRecorder.release();  
              mediaRecorder = null;  

              calendar = Calendar.getInstance();  
              teleEndTime = calendar.getTime().toString();  
              Message msg_end = new Message();  
              msg_end.what = TELE_END_TIME;  
              msg_end.obj = teleEndTime;  

              Log.d(TAG, "EndTime=====" + teleEndTime);  

              handler.sendMessage(msg_end);  
            }  
            Log.d(TAG, "結束錄音!");  
            break;  

        }  
      } catch (IllegalStateException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
      } catch (IOException e) {  
        // TODO Auto-generated catch block  
        e.printStackTrace();  
      }  
    }  
  }   
}  </pre> 


  1. 二、activity使用 

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener {

private TextView teleStartTime, teleEndTime;
private Button teleButton;
private TeleInterface teleInterface;
private TeleHandler teleHandler;
private EditText telNo;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
teleHandler = new TeleHandler(this, teleStartTime, teleEndTime);
teleInterface = new TeleInterface(this, teleHandler);
teleInterface.teleListen();
}

private void initView() {
teleStartTime = (TextView) findViewById(R.id.teleStartTime);
teleEndTime = (TextView) findViewById(R.id.teleEndTime);
teleButton = (Button) findViewById(R.id.teleButton);
telNo = (EditText) findViewById(R.id.telno);
teleButton.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.teleButton:
if(!telNo.getText().toString().trim().equals("")){
teleInterface.Call(telNo.getText().toString().trim());
}else{
teleInterface.Call("10010");
}

        try {  

// Thread.sleep(5000);
// teleInterface.sendDTMF("1".toCharArray()[0]);
teleInterface.endCall();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;

  default:  
    break;  
}  

}

} </pre>
三、布局配置文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
xmlns:tools="http://schemas.android.com/tools&quot;
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity" >

<EditText   
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:id="@+id/telno"  
    android:numeric="integer"  
    android:hint="電話號碼"/>  

<Button  
    android:id="@+id/teleButton"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="撥號" />  

<TextView  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="通話時間:" />  

<TextView  
    android:id="@+id/teleStartTime"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content" />  

<TextView  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content"  
    android:text="結束時間:" />  

<TextView  
    android:id="@+id/teleEndTime"  
    android:layout_width="wrap_content"  
    android:layout_height="wrap_content" />  

</LinearLayout></pre>

 本文由用戶 m45y 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!