I am working in call log project ,in that i can track the incoming and outgoing calls but tracking for last call duration is not accurate.When i track the last call duration the duration of previous call is shown to the current calls.
Initially i tried to track the duration for outgoing calls but it is not possible to track the outgoing calls by using the phone state listener so i fetched the last call duration in default phone call log.
I searched for stack overflow every one posted this answer but no one posted correct answer to track the last outgoing call duration.
This is my code
private int outgoingCallDuration(Context context) {
int sum = 0;
StringBuffer sb = new StringBuffer();
try {
//
Cursor managedCursor = context.getContentResolver().query(android.provider.CallLog.Calls.CONTENT_URI, null, null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
Log.e("total count", "" + managedCursor.getCount());
//managedCursor.moveToPosition(managedCursor.getCount() - 1);
int currentCount = 0, lastPosition = 0;
while (managedCursor.moveToNext()) {
currentCount++;
//managedCursor.moveToPosition(managedCursor.getCount() - 1);
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
java.sql.Date callDayTime = new java.sql.Date(Long.valueOf(callDate));
String callDurations = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
// lastPosition = currentCount;
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
lastPosition = currentCount;
}
lastPosition--;
managedCursor.moveToLast();
int requiredNumber = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int durations = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
String phNumber = managedCursor.getString(requiredNumber);
String dur = managedCursor.getString(durations);
// Long durat = Long.parseLong(dur);
int myNum = Integer.parseInt(dur);
managedCursor.close();
Log.e("last position number ", phNumber);
Log.e("last position duration ", dur);
return myNum;
} catch (SecurityException ex) {
Log.d("CallReceiver", "outgoingCallDuration: Permission to read call is not allowed by user!");
return 0;
}
}
In the above code i can track the last call duration.