import android.content.Context;
import android.media.MediaRecorder;
import android.os.Environment;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;/**
* Created by root on 4/4/17.
*/public class CallStateListener extends PhoneStateListener {
private DatabaseHelper databaseHelper=null;
private Context ctx;
public CallStateListener(Context cx) {
this.ctx=cx;
}
@Override
public void onCallStateChanged(int state,String Incomingnumber) {switch (state) {
case TelephonyManager.CALL_STATE_RINGING: //when phone is ringing
MainActivity.inCall = Incomingnumber;
MainActivity.wasRinging = true;
//Toast.makeText(ctx, "INCOMING : " + MainActivity.inCall, Toast.LENGTH_LONG).show();break;
case TelephonyManager.CALL_STATE_OFFHOOK: //when active or hold call
if(MainActivity.wasRinging==true) {
//Toast.makeText(ctx, "ANSWERED", Toast.LENGTH_LONG).show();
String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/CallRecorderApp");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = "Record_"+MainActivity.inCall;
try {
MainActivity.audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
MainActivity.recorder = new MediaRecorder();
// recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);MainActivity.recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
MainActivity.recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
MainActivity.recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
MainActivity.recorder.setOutputFile(MainActivity.audiofile.getAbsolutePath());
try {
MainActivity.recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
MainActivity.recorder.start();
MainActivity.recordstarted = true;
//saving above detail in database
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
databaseHelper=new DatabaseHelper(ctx);
databaseHelper.insert("inCall",MainActivity.inCall,strDate,MainActivity.audiofile.getAbsolutePath());
}break;
case TelephonyManager.CALL_STATE_IDLE:
MainActivity.wasRinging = false;
//Toast.makeText(ctx,"Reject or disconnected",Toast.LENGTH_LONG).show();
if (MainActivity.recordstarted) {
MainActivity.recorder.stop();
MainActivity.recordstarted = false;
Toast.makeText(ctx,"Call Recorded and saved",Toast.LENGTH_SHORT).show();
}break;
}}
}