Content Providers and finding Call logs.

There are two ways of finding out who’s been calling you with Android.

  • A listener class that detects an incoming/outgoing call
  • Polling the content provider to find the call log

It’s handier to use the latter rather than the former, as with the former, readings are being taken dynamically, but with the latter, the details of all the calls can be taken when needed, though if calls which occur before a certain point need to be discarded, an extra piece of code will be necessary.

To start, add the following to the project manifest file.

<uses-permission android:name=”android.permission.GET_ACCOUNTS” />
<uses-permission android:name=”android.permission.READ_CONTACTS” />
<uses-permission android:name=”android.permission.WRITE_CONTACTS” />

The code to poll the CallLog is shown below.

public void CallLog(){
String State= null;
Uri allCalls = Uri.parse(“content://call_log/calls”);
// Local address of CallLog
String[] projection = new String[]{Calls.TYPE, Calls.NUMBER, Calls.DATE,Calls.CACHED_NAME, Calls.DURATION};
//Details from the CallLog to be returned
Cursor c = managedQuery(allCalls, projection, null,null, Calls.DATE + ” DESC”);

// Calls are listed in order of date of occurance, with recent calls at the top

//Query the CallLog for details
if (c.moveToFirst())
{
do{ // For each result returned, the following occurs
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
String Date = c.getString(c.getColumnIndex(CallLog.Calls.DATE));
if (Double.parseDouble(Date)<TestTime){
TestTime = System.currentTimeMillis();

// check if this call occurred before the last time CallLog was invoked and method returns //if it was

return;
}
String Name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));
String Length = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
//Get details of the Call pulled down from the CallLog
String Type = null;
if (Name!=(null)){
State = Name;
}
else{
State = “No name”;
}
// Some numbers don’t have a name set, if no caller/target name set,
// null is set for the name
switch (type)
{
case 1: Type =  “Incoming”; break;
case 2: Type =  “Outgoing”; break;
case 3: Type =  “Missed”; break;
// 3 types of possible calls
}
State = State + “; ” + num + “; ” + Date + “;” + Type;
// Do something with data
}
while (c.moveToNext());
}

return;
}

That code will return information from the CallLog. Similiar code is used to retrieve data about SMS messages. For a good tutorial on SMS Content Providers, look here.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment