I have created one service and broadcast receiver to get telephony state.
Below is my code :
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_OUT);
filter.addAction(ACTION_IN);
if (br_call == null) {
br_call = new CallBr();
registerReceiver(br_call, filter);
}
return super.onStartCommand(intent, flags, startId);
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_IN)) {
if ((bundle = intent.getExtras()) != null) {
state =bundle.getString(TelephonyManager.EXTRA_STATE);
Log.d("tag", "state ::" + state);
if (!wasRinging) {
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
inCall=bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
wasRinging = true;
Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
}
}
if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
if (wasRinging) {
Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();
if (recorder == null) {
File sampleDir = new File(Environment.getExternalStorageDirectory(), "/RecordingDemo");
if (!sampleDir.exists()) {
sampleDir.mkdirs();
}
String file_name = inCall;
try {
audiofile = File.createTempFile(file_name, ".amr", sampleDir);
} catch (IOException e) {
e.printStackTrace();
}
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(audiofile.getAbsolutePath());
try {
recorder.prepare();
recorder.start();
recordstarted = true;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
wasRinging = false;
Toast.makeText(context, "REJECT || DISCONNECT", Toast.LENGTH_LONG).show();
if (recordstarted) {
try {
recorder.stop();
recordstarted = false;
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
}
}
if (intent.getAction().equals(ACTION_OUT)) {
if ((bundle = intent.getExtras()) != null) {
outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
}
}
}
}
I am facing below two issues
1) i have printed log in code for different states, but all states are printing multiple times and audio file is also created multiple times for same call.
2) if once i kill the app and start again, many times it wont record any calls. i have to add new build only.
Finally, I have found a solution. Please try following code.